算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+、-、*、/以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR。
输入样例:
+ + 2 * 3 - 7 4 / 8 4
输出样例:
13.0
#include<stdio.h>
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
string str;
stack<double> s;
getline(cin,str);
for(int i=str.length()-1;i>=0;i--){
if(str[i]>='0'&&str[i]<='9'){
string num="";
while(str[i]!=' '&&i!=0){
num=str[i]+num;
i--;
}
s.push(stof(num));
}else{
double a=s.top();
s.pop();
double b=s.top();
s.pop();
switch(str[i]){
case '+':s.push(a+b);break;
case '-':s.push(a-b);break;
case '*':s.push(a*b);break;
case '/':{
if(b==0){
printf("ERROR");
return 0;
}else{
s.push(a/b);
break;
}
}
default:break;
}
i--;//因为空格的存在
}
}
if(s.size()==1){
double result=s.top();
printf("%.1f",result);
}else{
printf("ERROR");
}
return 0;
}
需要注意的一点就是在读取完一个运算符号或者数字之后,i要减1,因为读入的时候中间是有空格的;读入有空格的string时用getline(cin,s)