求前缀表达式的值
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+、-、*、/以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR。
输入样例:
+ + 2 * 3 - 7 4 / 8 4
输出样例:
13.0
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 int main() 5 { 6 stack<float> s; 7 string a; 8 getline(cin,a); 9 10 int strlen=a.length(); 11 int i; 12 int t1,t2; 13 14 for(int i=strlen-1;i>=0; i--) 15 { 16 string b=""; 17 ///如果是符号 18 if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/') 19 { 20 t1=s.top(); 21 s.pop(); 22 t2=s.top(); 23 s.pop(); 24 if(t2==0&&a[i]=='/') 25 { 26 cout<<"ERROR"<<endl; 27 return 0; 28 } 29 if(a[i]== '+') s.push(t1+t2); 30 else if(a[i]== '-') s.push(t1-t2); 31 else if(a[i]== '*') s.push(t1*t2*1.0); 32 else if(a[i]== '/') s.push(t1*1.0/t2); 33 i--; 34 } 35 else 36 { 37 while(i>=0 && a[i]!=' ') //不要漏掉i>=0条件 38 { 39 b=a[i]+b; 40 i--; 41 } 42 //printf("atof:%f\n",atof(b.c_str())); 43 s.push(atof(b.c_str())); 44 } 45 } 46 if(s.size()==1) 47 printf("%0.1f\n",s.top()); 48 else 49 printf("ERROR\n"); 50 return 0; 51 52 }
浙公网安备 33010602011771号