1 + 2 4 + 2 * 5 - 7 / 11 0
3.00 13.36
#include <iostream> #include <stack> #include <sstream> #include <string> #include <iomanip> using namespace std ; stack<double> num ; stack<char> oper ; void compute(char op) { double a = num.top() ; num.pop() ; double b = num.top() ; num.pop() ; switch(op) { case '-' : num.push(b-a) ; break ; case '+' : num.push(b+a) ; break ; case '*' : num.push(b*a) ; break ; case '/' : num.push(b/a) ; break ; default : break ; } } int main() { string s ; while(getline(cin,s) && s != string("0")) { s.push_back(' ') ; s.push_back('=') ; stringstream st(s) ; int n ; char op ; while(st>>n>>op) { num.push(n) ; if(op == '+' || op == '-') { while(!oper.empty()) { char c = oper.top() ; oper.pop() ; compute(c) ; } oper.push(op) ; } else if(op == '*' || op == '/' ) { while(!oper.empty() && (oper.top() == '*' || oper.top() == '/' )) { char c = oper.top() ; oper.pop() ; compute(c) ; } oper.push(op) ; } else if(op == '=') { while(!oper.empty()) { char c = oper.top() ; compute(c) ; oper.pop() ; } cout << fixed << setprecision(2); cout << num.top() << endl; num.pop() ; break ; } } } return 0 ; }
原文地址:http://blog.csdn.net/lionel_d/article/details/44777949