好好学!
zhe道题和求后缀表达式的值可以相反过来做,从后面遍历,不过要注意的是操作数的处理,还有空格的跳过。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include<bits/stdc++.h> using namespace std;
int main() { string Str; stack<float> ans; getline(cin,Str); for(int i=Str.size()-1;i>=0;--i){ if(isdigit(Str[i])){ float mul=10,num=Str[i]-'0'; for(i--;i>=0;i--){ if(isdigit(Str[i])){ num+=(Str[i]-'0')*mul; mul*=10; } else if(Str[i]=='.'){ num/=mul; mul=1; } else if(Str[i]=='-') num=-num; else break; } ans.push(num); } else if(Str[i]==' ') continue; else { float a=ans.top(); ans.pop(); float b=ans.top(); ans.pop(); float tmp=0; if(Str[i]=='+') tmp=a+b; else if(Str[i]=='-') tmp=a-b; else if(Str[i]=='*') tmp=a*b; else if(Str[i]=='/'){ if(b==0){ cout<<"ERROR"; return 0; } tmp=a/b; } ans.push(tmp); } } printf("%.1f",ans.top()); return 0; }
|