Title description
Read in a non-negative integer calculation expression containing only +, -, *, /, and calculate the value of the expression.
enter
The test input contains several test cases, each test case occupies a line, each line does not exceed 200 characters, and the integer and the operator are separated by a space. There are no illegal expressions. When there is only 0 in a row, the input ends, and the corresponding result is not output.
Output
Output 1 line for each test case, that is, the value of the expression, accurate to 2 decimal places.
Sample input Copy
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92 0
Sample output Copy
12178.21
Problem-solving ideas:
1. Infix expression to postfix expression
2. Calculate the suffix expression
#include <iostream>
#include <cstdio>
#include <queue>
#include <stack>
#include <map>
using namespace std;
struct node
{
double data;
char ch;
int flag;
};
queue <node> q;
stack <node> s;
map<char,int> m;
string str;
void init()
{
while(!s.empty()) s.pop();
}
void change()///中缀转后缀
{
node t;
int n=str.size();
double cnt=0.0;
for(int i=0;i<n;i++){
if(str[i]>='0'&&str[i]<='9'){
cnt=cnt*10+str[i]-'0';
}
else if(str[i]!=' '){
t.flag=1;
t.data=cnt;
q.push(t);
cnt=0.0;
while(!s.empty()&&m[s.top().ch]>=m[str[i]]){
q.push(s.top());
s.pop();
}
t.flag=0;
t.ch=str[i];
s.push(t);
}
}
t.flag=1;
t.data=cnt;
q.push(t);
while(!s.empty()){
q.push(s.top());
s.pop();
}
}
void cal()///计算后缀表达式的值
{
node t;
while(!q.empty())
{
t=q.front();
q.pop();
if(t.flag==1) s.push(t);
else{
node x=s.top();s.pop();
node y=s.top();s.pop();
if(t.ch=='*') y.data*=x.data;
if(t.ch=='/') y.data/=x.data;
if(t.ch=='+') y.data+=x.data;
if(t.ch=='-') y.data-=x.data;
s.push(y);
}
}
double ans=s.top().data;
printf("%.2lf\n",ans);
}
int main()
{
m['+']=1;m['-']=1;
m['*']=2;m['/']=2;
while(getline(cin,str),str!="0"){
init();
change();
cal();
}
return 0;
}