//stack应用:表达式求值 //无括号四则运算通用模版 #include <iostream> #include <cctype>//isdigit(str[index]) #include <stack> using namespace std; double GetNumber(string str,int& index) { double number=0; while(isdigit(str[index])) { number=number*10+str[index]-'0'; index++; } return number; } int Prior(char op) { if(op=='#')return 0; else if(op=='$')return 1; else if(op=='+'||op=='-')return 2; else return 3; } double Calculate(double x,double y,char op) { double result=0; if(op=='+')result=x+y; else if(op=='-')result=x-y; else if(op=='*')result=x*y; else result=x/y; return result; } int main() { string str; while (getline(cin,str)) { if(str==" ")break; int index=0; stack<double> num; stack<char> oper; oper.push('#');//优先级最小 str+='$';///有必要 因为当栈内剩下最后一个+/*-运算符时,需要$来将其预算掉 while(index<str.size()) { if(isdigit(str[index])) { num.push(GetNumber(str,index)); } else if(Prior(oper.top())<Prior(str[index])) { oper.push(str[index]); index++; } else { double y=num.top(); num.pop(); double x=num.top(); num.pop(); num.push(Calculate(x,y,oper.top())); oper.pop(); } } cout<<num.top()<<endl; } }