//stack应用:表达式求值 /* //不知道错哪了:一直说我有段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起 //此方法没有考虑整数是多位数!! #include <iostream> #include <stack> using namespace std; int main() { stack<double> num; stack<char> fu; string ans; fu.push('#'); while(cin>>ans) { if(ans=="0")break; for(int i=0;i<ans.size();i++) { if(ans[i]!=' ') { if((ans[i]-'0')>=0&&(ans[i]-'0')<=9) { num.push(ans[i]-'0'); // cout<<num.top()<<" ";// } else { fu.push(ans[i]); // cout<<fu.top()<<" ";// } } } while(fu.top()!='#')/////判断条件 { double number=num.top();//暂存数字 num.pop(); if(fu.top()=='/'||fu.top()=='*') { char fuhao=fu.top();//暂存符号 fu.pop(); double n2; if(fuhao=='/') { n2=num.top(); num.pop(); double n3=(n2*1.0)/(number); num.push(n3); } else if(fuhao=='*') { n2=num.top(); num.pop(); double n3=(n2*1.0)*(number); num.push(n3); } } else if(fu.top()=='+'||fu.top()=='-') { char fu1;//暂存栈顶符号 fu1=fu.top(); fu.pop(); if(fu.top()=='+'||fu.top()=='-'||fu.empty()) { double shu1; shu1=num.top(); num.pop(); if(fu1=='+') { shu1=shu1+number; } else { shu1=shu1-number; } num.push(shu1); } else if(fu.top()=='/'||fu.top()=='*') { double shuh;//5 double shuq;//2 shuh=num.top(); num.pop(); shuq=num.top(); num.pop(); if(fu.top()=='/') { shuq=shuq*1.0/shuh; num.push(shuq); } else{ shuq=shuq*1.0*shuh; num.push(shuq); } fu.pop(); num.push(number); fu.push(fu1); } } } printf("%.2f\n",num.top()); } return 0; } */ #include <iostream> #include <stack> #include <cctype> using namespace std; int Prior(char x) { if(x=='#')return 1; else if(x=='$')return 2; else if(x=='+'||x=='-')return 3; else return 4; //else if(x=='*'||x=='/')return 4; //写成这样会报错,说函数没有返回值 } double GetNumber(string str,int& index)//传引用,形参变化,实参也变 { double number=0; while(isdigit(str[index])) { number=number*10+str[index]-'0'; index++; } return number; } 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=="0")break; int index=0; stack<double> data; stack<char> oper; str+='$'; oper.push('#'); while(index<str.size()) { if(str[index]==' ')index++; else if(isdigit(str[index])) data.push(GetNumber(str,index)); else if(Prior(oper.top())<Prior(str[index]))//不能写成<= 因为优先级相同时,从左往右运算 { oper.push(str[index]); index++; } else { double y=data.top(); data.pop(); double x=data.top(); data.pop(); data.push(Calculate(x,y,oper.top())); oper.pop(); } } printf("%.2f\n",data.top()); } return 0; }