进阶实验3-3.1 求前缀表达式的值 (25分)

进阶实验3-3.1 求前缀表达式的值 (25分)

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。

输入格式:

输入在一行内给出不超过30个字符的前缀表达式,只包含+-*/以及运算数,不同对象(运算数、运算符号)之间以空格分隔。

输出格式:

输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR

输入样例:

+ + 2 * 3 - 7 4 / 8 4
 

输出样例:

13.0
思路很简单,就是从后往前遍历,用栈维护。主要注意一下怎么字符串转double和int。挂一下大佬博客:http://www.luyixian.cn/news_show_235099.aspx
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<stack>
 5 #include<cstdlib>
 6 #include<algorithm>
 7 using namespace std;
 8 const int maxn=50;
 9 string c[maxn];
10 int cnt;
11 stack<double>st;
12 int main()
13 {
14     while(cin>>c[cnt])
15     {
16         cnt++;
17     }
18     for(int i=cnt-1;i>=0;i--)
19     {
20         if(c[i]=="+"||c[i]=="-"||c[i]=="*"||c[i]=="/")
21         {
22             if(st.empty())
23             {
24                 cout<<"ERROR"<<endl;
25                 return 0;
26             }
27             double x=st.top();
28             st.pop();
29             if(st.empty())
30             {
31                 cout<<"ERROR"<<endl;
32                 return 0;
33             }
34             double y=st.top();
35             st.pop();
36             if(c[i]=="+")
37                 st.push(x+y);
38             if(c[i]=="-")
39                 st.push(x-y);
40             if(c[i]=="*")
41                 st.push(x*y);
42             if(c[i]=="/")
43             {
44                 if(y==0)
45                 {
46                     cout<<"ERROR"<<endl;
47                     return 0;
48                 }    
49                 st.push(x/y); 
50             }
51             
52         }
53         else
54         {
55             double x=atof(c[i].c_str());
56         //    cout<<"x="<<x<<endl;
57             st.push(x);
58         }
59     }
60     printf("%.1f\n",st.top());
61     return 0;
62 } 

 

posted @ 2020-04-07 20:32  *starry*  阅读(624)  评论(0编辑  收藏  举报