Enter a non-negative integer expression containing only + - * / to calculate the value of the expression.
[thinking]
1. Set up two stacks, one for saving operators and the other for saving numbers.
2. Traversing a string from left to right, if the top operator of the operator stack has a lower priority than the operator or if the operator stack is empty at this time, the operator is pushed onto the stack.
3. If the operator stack top operator priority is greater than the operator, pop up the stack top operator, then pop up two stack top numbers from the digital stack, calculate, and push the results into the digital stack, repeat the comparison of the stack top operator and the current traversal operator priority, repeat steps 2 or 3 as appropriate.
4. If you traverse the number, press it directly into the digital stack
5. If there are operators on the operator stack, pop operators and two numeric operators are computed until there are no operators.
[Sample Input and Output] 4+2*5-7/11 Output 13.36
#include<iostream> #include<stack> #include<string.h> #include<iomanip> #include<map> #include<algorithm> using namespace std; stack<char> opr; stack<double> in; std::map<char, int> m; double compute(double a,double b,char c) { if(c=='+') return a+b; else if(c=='-') return a-b; else if(c=='*') return a*b; else if(c=='/') return a/b; } int main(int argc, char const *argv[]) { m['+']=1; m['-']=1; m['*']=2; m['/']=2; int i; double a,b,temp; char input[100]; while(cin>>input) { for(i=0;input[i]!=0;i++) { if((input[i]>='0')&&(input[i]<='9')) { temp=input[i]-'0'; while(input[i+1]>='0'&&input[i+1]<='9')//Multi-digit situation { temp=temp*10+input[i+1]-'0'; i++; } in.push(temp);// Don't forget to convert character numbers into double numbers cout<<in.top()<<endl; } else { if(opr.empty()||m[opr.top()]<=m[input[i]]) opr.push(input[i]); else { while(m[opr.top()]>m[input[i]])// Loop when the priority of the top element of the stack is greater than that of the element { b=in.top(); in.pop(); a=in.top(); in.pop(); in.push(compute(a,b,opr.top())); opr.pop(); } opr.push(input[i]); } } } while(!opr.empty()) { b=in.top(); in.pop(); a=in.top(); in.pop(); in.push(compute(a,b,opr.top()));//Who is in the front and who is behind wrong? opr.pop(); } cout<<fixed<<setprecision(2)<<in.top()<<endl;//Keep two decimal places } return 0; }