题目
前缀表达式是一种把运算符前置的算术表达式,例如普通的表达式 2+32+3 的波兰表示法为 + 2 3+ 2 3 。波兰表达式的优点是运算符之间不必有优先级关系,也不必用括号改变运算次序,例如 (2+3)∗4(2+3)∗4 的波兰表示法为 ∗ + 2 3 4∗ + 2 3 4。
本题求解波兰表达式的值,其中运算符包括 + - * /四个。
解法1:栈
//前缀表达式可以看作反写后缀表达式,用栈实现反转即可
//后缀表达式链接:https://blog.csdn.net/2301_77744823/article/details/141255774?spm=1001.2014.3001.5502
#include <bits/stdc++.h>
using namespace std;
stack<double>num;
stack<string>st;
int main(){
string s;
int x;
while(cin>>s)st.push(s);
while(st.size()){
s=st.top();
st.pop();
if(s[0]>='0'&&s[0]<='9'){
stringstream sin;
sin<<s;
sin>>x;
num.push(double(x));
}
else{
double a,b;
b=num.top();
num.pop();
a=num.top();
num.pop();
if(s[0]=='+')num.push(a+b);
if(s[0]=='-')num.push(a-b);
if(s[0]=='*')num.push(a*b);
if(s[0]=='/')num.push(a/b);
}
}
cout<<fixed<<setprecision(3)<<num.top();
return 0;
}
解法2:递归(表达式树)
上图展示的为前缀表达式 + 13 * 5 9 的表达式树
#include <bits/stdc++.h>
using namespace std;
double cal(){
string s;
cin>>s;
//符号,递归下降
if(s=="+")return cal()+cal();
if(s=="-")return cal()-cal();
if(s=="*")return cal()*cal();
if(s=="/")return cal()/cal();
return stof(s);//数字,转成浮点数
}
int main(){
cout<<fixed<<setprecision(3)<<cal();
return 0;
}