A pesar de que el algoritmo es principio muy simple, pero hay algunas áreas que requieren atención.
1. Debido a que el paréntesis izquierdo es para ser colocado en el registro del operador, por lo que su prioridad se establece en 0, o para otros operadores, y no saben que no pueden entrar.
2. La parte superior de la pila es inferior a la prioridad de la op operador, el operador puede ser colocado en la pila.
#include <bits/stdc++.h>
using namespace std;
struct node {
double num;
char op;
bool flag;
};
string str;
stack<node>s;
queue<node>q;
map<char,int>op;
void change() {
double num;
node temp;
for(int i=0;i<str.length();i++) {
char c=str[i];
if(c>='0'&&c<='9') {
temp.flag=true;
temp.num=c-'0';
q.push(temp);
} else {
if(c==')') {
while(!s.empty() &&s.top().op!='(') {
q.push(s.top());
s.pop();
}
s.pop();
continue;
} else if(c!='('){
while(!s.empty() && op[c]<=op[s.top().op]) {
q.push(s.top());
s.pop();
}
}temp.flag=false;
temp.op=c;
s.push(temp);
}
}
while(!s.empty()){
q.push(s.top());
s.pop();
}//从操作符栈变成了空栈
}
double cal(){
double temp1,temp2;
node cur,temp;
while(!q.empty()){
cur=q.front();
q.pop();
if(cur.flag==true)s.push(cur);
else {
temp2=s.top().num;
s.pop();
temp1=s.top().num;
s.pop();
temp.flag=true;
if(cur.op=='+')temp.num=temp1+temp2;
if(cur.op=='-')temp.num=temp1-temp2;
if(cur.op=='*')temp.num=temp1*temp2;
if(cur.op=='/')temp.num=temp1/temp2;
s.push(temp);
}
}return s.top().num;
}
int main(int argc, char **argv) {
op['(']=0;
op['+']=op['-']=1;
op['*']=op['/']=2;
getline(cin,str);
change();
printf("%.2f",cal());
return 0;
}