注意细节!
返回值要写全所有情况,哪怕输入有限制
取数和计算时要i--,避免后续的i++而跳过字符(或者改用while写,相应位置i++)
最后最好清空栈(虽然不清空并不影响结果)
#include<iostream>
#include<string>
#include<stack>
using namespace std;
string s;
stack<char>sign;
stack<double>number;
int priority(char c){//return 所有情况要写完整
if(c=='#')return 0;
else if(c=='+'||c=='-')return 3;
else if(c=='*'||c=='/')return 4;
else if(c=='$')return 2;
else return 5;
}
double calculate(double x,double y,char op){
if(op=='+')return x+y;
else if(op=='-')return x-y;
else if(op=='*')return x*y;
else if(op=='/')return x/y;
else return 0;
}
double getnumber(string s,int &t){
double x=0;
while(s[t]>='0'&&s[t]<='9'){//条件写严格
x=x*10+s[t]-'0';
t++;
}
return x;
}
int main(){
while(getline(cin,s)){
if(s=="0")break;
double answer=0;
sign.push('#');
s=s+" $";//保持格式一致性
for(int i=0;i<s.size();i++){
if(s[i]==' ')continue;
else if(s[i]>='0'&&s[i]<='9'){
number.push(getnumber(s,i));
i--;//不跳过
}
else{
if(priority(s[i])<=priority(sign.top())){
double y=number.top();
number.pop();
double x=number.top();
number.pop();
char op=sign.top();
sign.pop();
number.push(calculate(x,y,op));
i--;//不跳过
}
else sign.push(s[i]);
}
}
printf("%.2lf\n",number.top());
while(!sign.empty())sign.pop();//清空符号栈
while(!number.empty())number.pop();//清空数据栈
}
return 0;
}