codeup墓地 问题 A: 简单计算器
#include<iostream>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<cstring>
#include<iomanip>
using namespace std;
map<char, int> p;
void dealpre(string &pre, string &bac, stack<char> &ope){
int i, prelen = pre.size();
for(i = 0; i < prelen; i++){
if(('0' <= pre[i] && pre[i] <= '9') || pre[i] == ' '){
bac += pre[i];
} else if(pre[i] == '+' || pre[i] == '-' || pre[i] == '*' || pre[i] == '/'){
if(ope.empty() || p[pre[i]] > p[ope.top()]) ope.push(pre[i]);
else{
while(!ope.empty() && p[ope.top()] >= p[pre[i]]){
bac += ope.top();
ope.pop();
}
ope.push(pre[i]);
}
}
}
while(!ope.empty()){
bac += ope.top();
ope.pop();
}
return;
}
double calculate(string &bac, stack<double> &ans){
int i, baclen = bac.size();
double num = 0, temp1, temp2;
bool flag = true;
bool judge = false;
for(i = 0; i < baclen; i++){
if('0' <= bac[i] && bac[i] <= '9'){
num = num * 10 + bac[i] - '0';
flag = true;
} else if(bac[i] == ' '){
if(flag){
ans.push(num);
num = 0;
flag = false;
}
} else{
if(!judge && (i == baclen - 2 || i == baclen - 1)){
ans.push(num);
num = 0;
judge = true;
}
if(!ans.empty()){
temp2 = ans.top();
ans.pop();
}
if(!ans.empty()){
temp1 = ans.top();
ans.pop();
}
switch(bac[i]){
case '+':
ans.push(temp1 + temp2);
break;
case '-':
ans.push(temp1 - temp2);
break;
case '*':
ans.push(temp1 * temp2);
break;
case '/':
ans.push(temp1 / temp2);
break;
}
}
}
return ans.top();
}
int main(){
p['*'] = 1;
p['/'] = 1;
p['+'] = 0;
p['-'] = 0;
string pre;
getline(cin, pre);
while(pre != "0"){
string bac;
stack<char> ope;
stack<double> ans;
dealpre(pre, bac, ope);
cout << setiosflags(ios::fixed) << setprecision(2) << calculate(bac, ans) << endl;
getline(cin, pre);
}
return 0;
}