#include <iostream>
#include <cstring>
#include <cstdio>
#include<queue>
#include<string>
#include<stack>
using namespace std;
int pri[5][5] = {
1,0,0,0,0,
1,0,0,0,0,
1,0,0,0,0,
1,1,1,0,0,
1,1,1,0,0
};
char str[220];
stack<int>op;
stack<double>in;
void getOp(bool &reto,int &retn,int &i){
if(i == 0 && op.empty()){
reto = true;
retn = 0;
return;
}
if(str[i] == 0){
reto = true;
retn = 0;
return;
}
if(str[i] >= '0' && str[i] <= '9'){
reto = false;
retn = 0;
}
else{
reto = true;
if(str[i] == '+') retn = 1;
else if (str[i] == '-') retn = 2;
else if (str[i] == '*') retn = 3;
else if (str[i] == '/') retn = 4;
i += 2;
return;
}
for(;str[i] != ' ' && str[i] != 0;++i){
retn *= 10;
retn += str[i] - '0';
}
if(str[i] == ' ')++i;
return;
}
int main(){
while(gets(str) ){
if(str[0] == '0' && str[1] == 0)break;
int retn;bool reto; int idx = 0;
while(!op.empty())op.pop();
while(!in.empty())in.pop();
while(1){
getOp(reto,retn,idx);
if(!reto){
in.push((double)retn);
}
else{
if(op.empty() || pri[retn][op.top()] == 1)op.push(retn);
else{
while(pri[retn][op.top()] == 0){
int tmp = op.top();
op.pop();
double b = in.top();
in.pop();
double a = in.top();
in.pop();
if(tmp == 1)in.push(a+b);
if(tmp == 2)in.push(a-b);
if(tmp == 3)in.push(a*b);
if(tmp == 4)in.push(a/b);
}
op.push(retn);
}
}
if(op.size() == 2 && op.top()== 0){
break;
}
}
printf("%.2f\n",in.top());
}
return 0;
}
表达式求值(堆栈经典应用)
最新推荐文章于 2023-05-30 20:38:07 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)