我们人类习惯于书写“中缀式”,如 3 + 5 * 2 ,其值为13。 (p.s. 为什么人类习惯中缀式呢?是因为中缀式比后缀式好用么?)
而计算机更加习惯“后缀式”(也叫“逆波兰式”,Reverse Polish Notation)。上述中缀式对应的后缀式是: 3 5 2 * +
现在,请对输入的后缀式进行求值。
输入格式:
在一行中输入一个后缀式,运算数和运算符之间用空格分隔,运算数长度不超过6位,运算符仅有+ - * / 四种。
输出格式:
在一行中输出后缀式的值,保留一位小数。
输入样例:
3 5.4 2.2 * +
输出样例:
14.9
#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
#include<deque>
using namespace std;
int main() {
stack<double>st;
string s;
getline(cin,s);
for(int i=0;i<s.size();){
string temp;
while(i<s.size()&&s[i]!=' '){
temp+=s[i];
i++;
}
i++;
if(temp.size()==1&&temp[0]=='+'){
double t2=st.top();
st.pop();
double t1=st.top();
st.pop();
st.push(t1+t2);
}
else if(temp.size()==1&&temp[0]=='-'){
double t2=st.top();
st.pop();
double t1=st.top();
st.pop();
st.push(t1-t2);
}
else if(temp.size()==1&&temp[0]=='*'){
double t2=st.top();
st.pop();
double t1=st.top();
st.pop();
st.push(t1*t2);
}
else if(temp.size()==1&&temp[0]=='/'){
double t2=st.top();
st.pop();
double t1=st.top();
st.pop();
if(!t2){
cout<<"ERROR";
return 0;
}
st.push(t1/t2);
}
else{
st.push(stod(temp));
}
}
if(!st.empty()){
printf("%.1f",st.top());
}
return 0;
}
我发现我每次写的都不一样,感觉下面的版本更好理解
#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
#include<deque>
#include<cctype>
using namespace std;
int main() {
string s;
getline(cin,s);
stack<double>st;
for(int i=0;i<s.length();i++){
string temp;
if(s[i]==' '){
continue;
}
if((isdigit(s[i+1])&&(s[i]=='+'||s[i]=='-'))||isdigit(s[i])||s[i]=='.'){
if(s[i]=='+'){
temp="";
}
else{
temp=s[i];
}
while(isdigit(s[i+1])||s[i+1]=='.'){
temp+=s[i+1];
i++;
}
st.push(stod(temp));
}
else{
double t1=st.top();
st.pop();
double t2=st.top();
st.pop();
if(s[i]=='+'){
st.push(t1+t2);
}
else if(s[i]=='-'){
st.push(t2-t1);
}
else if(s[i]=='*'){
st.push(t1*t2);
}
else if(s[i]=='/'){
if(!t1){
cout<<"ERROR";
return 0;
}
st.push(t2/t1);
}
}
}
printf("%.1f",st.top());
return 0;
}