http://codeup.cn/problem.php?cid=100000605&pid=0

    读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。

    1. #include<iostream>
    2. #include<map>
    3. #include<stack>
    4. using namespace std;
    5. stack<char> op;
    6. stack<double> st;
    7. void cal(){
    8. char c = op.top(); op.pop();
    9. double num1 = st.top();st.pop();
    10. double num2 = st.top(); st.pop();
    11. switch(c){
    12. case '+':st.push(num2+num1);break;
    13. case '-':st.push(num2-num1);break;
    14. case '*':st.push(num2*num1);break;
    15. case '/':st.push(num2/num1);break;
    16. }
    17. }
    18. double solve(string s){
    19. map<char,int> f;
    20. f['+']= 1, f['-'] = 1, f['*']=2,f['/']=2;
    21. for(int i=0;i<s.length();i++){
    22. if(i<s.length()&&isdigit(s[i])){
    23. int ans = 0;
    24. while(i<s.length()&&isdigit(s[i])){
    25. ans = ans*10+ s[i]-'0';i++;
    26. }
    27. st.push(ans);
    28. }
    29. if(i<s.length()&&!isdigit(s[i])){
    30. if(op.size()==0||f[s[i]]>f[op.top()]){
    31. op.push(s[i]);
    32. }
    33. else {
    34. while(op.size()&&f[s[i]]<=f[op.top()]){
    35. cal();
    36. }
    37. op.push(s[i]);
    38. }
    39. }
    40. }
    41. while(op.size()) cal();
    42. return st.top();
    43. }
    44. int main(){
    45. string s;
    46. while(getline(cin,s)&&s!="0"){
    47. for(auto it=s.end();it!=s.begin();it--){
    48. if(*it==' ') s.erase(it);
    49. }
    50. // cout << s << endl;
    51. double res = solve(s);
    52. printf("%.2lf\n",res);
    53. }
    54. return 0;
    55. }