模拟计算器
#include <iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<map>
using namespace std;
struct node {
int num;
char op;
bool type;
};
queue<node> Q;
stack<node> S;
map<char, int> M;
void change(string str){
node node1;
for(int i = 0; i < str.length();){
if(str[i] >= '0' && str[i] <= '9'){
node1.num = str[i++] - '0';
node1.type = true;
while( i < str.length() && str[i] >= '0' && str[i] <= '9' ){
node1.num = node1.num * 10 + (str[i] - '0');
i ++;
}
Q.push(node1);
}
else if(str[i] != ' '){
char c = str[i];
if(c == ')'){
while(!S.empty() && S.top().op != '('){
Q.push(S.top());
S.pop();
}
S.pop();
}
else{
while(!S.empty() && M[c] <= M[S.top().op]){
Q.push(S.top());
S.pop();
}
node1.op = c;
node1.type = false;
S.push(node1);
}
i ++;
}
else i ++;
}
while(!S.empty()){
Q.push(S.top());
S.pop();
}
}
double calculate(){
stack<int> helper;
while(!Q.empty()){
node temp = Q.front();
Q.pop();
if(temp.type){
helper.push(temp.num);
}
else{
double a1 = helper.top();
helper.pop();
double a2 = helper.top();
helper.pop();
double res = 0.0;
if(temp.op == '+') res = a1 + a2;
else if(temp.op == '-') res = a1 - a2;
else if(temp.op == '*') res = a1 * a2;
else if(temp.op == '/') res = a1 / a2;
helper.push(res);
}
}
return helper.top();
}
int main()
{
M['+'] = M['-'] = 1;
M['*'] = M['/'] = 2;
M['('] = 0;
M[')'] = 1;
string str;
getline(cin, str);
change(str);
printf("%.2f", calculate());
system("pause");
return 0;
}