#include<queue>
#include<map>
#include<stack>
#include<algorithm>
#include<string>
#include<iostream>
#include<cstdio>
using namespace std;
struct node{
double num;
char op;
bool flag;
};
string str;
stack<node> o;
queue<node> h;
map<char,int> op;
void change(){
// double sum;
node tmp;
for(int i=0;i<str.size();){
if(str[i]>='0'&&str[i]<='9'){
tmp.flag=true;
tmp.num=str[i++]-'0';//注意这里i要自增!!!!
while(i<str.size()&&(str[i]>='0'&&str[i]<='9')){
tmp.num=tmp.num*10+str[i]-'0';
i++;
}
h.push(tmp);
}else{
tmp.flag=false;
while(!o.empty()&&(op[str[i]]<=op[o.top().op])){
h.push(o.top());
o.pop();
}
tmp.op=str[i];
o.push(tmp);
i++;
}
}
while(!o.empty()){
h.push(o.top());
o.pop();
}
}
double com(){
double tmp1,tmp2;
node cur,tmp;
while(!h.empty()){
cur=h.front();
h.pop();
if(cur.flag==true){
o.push(cur);
}else{
tmp2=o.top().num;
o.pop();
tmp1=o.top().num;
o.pop();
tmp.flag=true;
if(cur.op=='+') tmp.num=tmp1+tmp2;
else if(cur.op=='-') tmp.num=tmp1-tmp2;
else if(cur.op=='*') tmp.num=tmp1*tmp2;
else tmp.num=tmp1/tmp2;
o.push(tmp);
}
}
return o.top().num;
}
int main(){
// int i;//此处千万不能直接定义在循环外面!
op['+']=op['-']=1;
op['*']=op['/']=2;
while(getline(cin,str),str!="0"){
for(int i=0;i<str.size();i++){
if(str[i]==' ')
str.erase(str.begin()+i);
}
// cout<<str;
//cout<<str.size();
while(!o.empty()) o.pop();//初始化栈!!!!!
change();
printf("%.2f\n",com());
}
return 0;
}
codeup1918 简单计算器
最新推荐文章于 2021-02-20 11:32:38 发布