中缀表达式转后缀表达式 :
扫描中缀表达式:
1.数字,直接输出
2.左括号,左括号入栈
3.右括号,不断取栈顶并输出,直到栈顶为左括号,最后左括号出栈
4.运算符,不断取栈顶并输出,直栈顶优先级高于此运算符,最后新运算符入栈
后缀表达式求值:
扫描后缀表达式:
1.数字,入栈
2.运算符,取出栈顶两个数,运算,结果入栈
3.最后栈里剩下的一个数即为答案
#include<iostream>
#include<iomanip>
#include<unordered_map>
#include<stack>
#include<string>
using namespace std;
inline double cal(double a,double b,char op){
switch(op){
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':return a/b;
}
return 0;
}
string::iterator i;
inline double dio(){
double x=0;
while(isdigit(*i))x=x*10+*i-'0',++i;
return x;
}
unordered_map<char,int>op;
stack<char>sta;
stack<double>st;
string s;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
op['(']=op[')']=0;
op['+']=op['-']=1;
op['*']=op['/']=2;
while(getline(cin,s)){
if(s=="0")break;
string suffix;
i=s.begin();
while(i!=s.end()){
if(op.count(*i)){
if(*i==')'){
while(sta.top()!='(')suffix+=sta.top(),sta.pop();
sta.pop();
}else if(sta.empty()||*i=='('||op[sta.top()]<op[*i])sta.push(*i);
else if(op[sta.top()]>=op[*i]){
while(!sta.empty()&&op[sta.top()]>=op[*i])suffix+=sta.top(),sta.pop();
sta.push(*i);
}
}else suffix+=*i;
++i;
if(i==s.end()){
suffix+=' ';
while(!sta.empty())suffix+=sta.top(),sta.pop();
}
}
cout<<suffix<<'\n';
i=suffix.begin();
double a,b;
while(i!=suffix.end()){
if(op.count(*i)){
a=st.top(),st.pop();
b=st.top(),st.pop();
st.push(cal(b,a,*i));
}else if(*i!=' ')st.push(dio());
++i;
}
cout<<setiosflags(ios::fixed)<<setprecision(2)<<st.top()<<'\n';
st.pop();
}
return 0;
}