给出一个算式字符串,计算出结果
核心思路:
- 构造两个栈,一个栈存放数字,一个栈存放运算符
- 运算符栈压栈时,压栈元素应优先级应大于top,小于或等于则弹出栈顶元素,进行计算,反复操作
#include<iostream>
#include<stack>
#include<string>
using namespace std;
class Solution{
public:
int getNumber(string str){
int num=0;
for(char s:str){
num=num*10+(s-'0');
}
return num;
}
int getProtity(char c){
if(c=='*'||c=='/'){
return 0;
}else if(c=='+'||c=='-'){
return 1;
}else if(c=='$'){
return 2;
}
}
double calculate(double num1,double num2, char operate){
switch(operate){
case '+': return num1+num2;
case '-': return num2-num1;
case '*': return num1*num2;
case '/': return num2*1.0/num1;
}
}
};
int main(){
Solution solution;
string expression;
while(getline(cin,expression)){
if(expression.size()==1&&expression[0]=='0'){
return 0;
}
stack<double> number;
stack<char> eval;
eval.push('$');
string numStr = "";
int pro;
for(int i=0;i<expression.size();i++){
while(expression[i]<='9'&&expression[i]>='0'){
numStr+=expression[i];
i++;
}
if(numStr!=""){
if(i==30){
int ccc=0;
}
number.push(solution.getNumber(numStr));
numStr = "";
i--;
}
if(expression[i]=='+'||expression[i]=='-'||expression[i]=='*'||expression[i]=='/'){
while(solution.getProtity(expression[i])>=solution.getProtity(eval.top())){
double num1 = number.top();
number.pop();
double num2 = number.top();
number.pop();
number.push(solution.calculate(num1,num2, eval.top()));
eval.pop();
}
eval.push(expression[i]);
}
}
while(eval.top()!='$'){
double num1 = number.top();number.pop();
double num2 = number.top();number.pop();
number.push(solution.calculate(num1, num2, eval.top()));
eval.pop();
}
printf("%.2f\n",number.top());
}
return 0;
}