进阶实验3-3.1 求前缀表达式的值 (25分)
求前缀表达式的值需要从后往前读,其他和后缀表达式求值方式相同,利用堆栈求值
输入样例
“ + + 2 * 3 - 7 4 / 8 ”
输出样例
13.0
运行结果
代码
#include <iostream>
#include <iomanip>
#include <stack>
#include <cstring>
#include <cmath>
using namespace std;
stack<double> num;
bool flag=true;
double sum=0;
bool operation(char letter){
int temp1,temp2;
if(!num.empty()){
temp1=num.top();
num.pop();
} else{
cout<<"ERROR";
return false;
}
if(!num.empty()){
temp2=num.top();
num.pop();
} else{
cout<<"ERROR";
return false;
}
switch (letter){
case '+':num.push(temp1 + temp2);
break;
case '-':num.push(temp1 - temp2);
break;
case '*':num.push(temp1 * temp2);
break;
case '/':if(temp2==0){
cout<<"ERROR";
return false;
}
else
num.push(temp1 / (temp2*1.0));
break;
}
return true;
}
int main()
{
char s[71];
cin.getline(s,71);
for (int i = strlen(s)-1; i >=0 ; --i) { //从后往前读
string digitStr="";
switch (s[i]){
case '+':flag=operation(s[i]);
break;
case '-':flag=operation(s[i]);
break;
case '*':flag=operation(s[i]);
break;
case '/':flag=operation(s[i]);
break;
}
if(s[i]<='9'&&s[i]>='0'){
while(i>=0 && s[i]!=' ') //不要漏掉i>=0条件
{
digitStr=s[i]+digitStr;
--i;
} //读数
//printf("atof:%f\n",atof(digitStr.c_str()));
num.push(atof(digitStr.c_str()));
}
}
if(flag){
sum=num.top();
cout << fixed << setprecision(1) << sum;
}
return 0;
}