4132:四则运算表达式求值(栈)

总时间限制: 

1000ms
 
内存限制: 
65536kB
描述

求一个可以带括号的小学算术四则运算表达式的值

输入
一行,一个四则运算表达式。'*'表示乘法,'/'表示除法
输出
一行,该表达式的值,保留小数点后面两位
样例输入
输入样例1:
3.4
输入样例2:
7+8.3
输入样例3:
3+4.5*(7+2)*(3)*((3+4)*(2+3.5)/(4+5))-34*(7-(2+3))
样例输出
输出样例1:
3.40
输出样例2:
15.30
输出样例3:
454.75

 思路:先把中缀表达式转化为后缀表达式,然后再求值

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 struct node {
 5     double num;
 6     char op;
 7     bool flag;
 8 };
 9 stack <node> s;
10 queue <node> q;
11 map <char,int> mp;
12 string str;
13 void change() {//把中缀表达式转化为后缀表达式
14     node temp;
15     for(int i=0; i<str.length();) {
16         if(str[i]>='0'&&str[i]<='9'&&i<str.length()||str[i]=='.') {
17             temp.num=0;
18             temp.flag=1;
19             while(str[i]>='0'&&str[i]<='9'&&i<str.length()) {
20                 temp.num=temp.num*10+(str[i]-'0');
21                 i++;
22             }
23             if(str[i]=='.') {
24                 i++;
25                 int ii=0;
26                 while(str[i]>='0'&&str[i]<='9'&&i<str.length()) {
27                     ii++;
28                     temp.num+=pow(0.1,ii)*(str[i]-'0');
29                     i++;
30                 }
31             }
32             q.push(temp);
33         } else {
34             if(str[i]=='('||s.empty()||mp[str[i]]>mp[s.top().op]) {
35                 temp.flag=0;
36                 temp.op=str[i];
37                 s.push(temp);
38                 i++;
39             } else if(str[i]==')') {
40                 while(s.top().op!='(') {
41                     q.push(s.top());
42                     s.pop();
43                 }
44                 i++;
45                 s.pop();
46             } else {
47                 while(!s.empty()&&mp[str[i]]<=mp[s.top().op]&&s.top().op!='(') {
48                     q.push(s.top());
49                     s.pop();
50                 }
51                 temp.flag=0;
52                 temp.op=str[i];
53                 s.push(temp);
54                 i++;
55             }
56         }
57     }
58     while(!s.empty()) {
59         q.push(s.top());
60         s.pop();
61     }
62 }
63 double cal() {//对后缀表达式进行计算
64     double a1,a2;
65     node temp,now;
66     while(!q.empty()) {
67         now=q.front();
68         q.pop();
69         if(now.flag==1) {
70             s.push(now);
71         } else {
72             a2=s.top().num;
73             s.pop();
74             a1=s.top().num;
75             s.pop();
76             if(now.op=='+')temp.num=a1+a2;
77             else if(now.op=='-')temp.num=a1-a2;
78             else if(now.op=='*')temp.num=a1*a2;
79             else if(now.op=='/')temp.num=a1/a2;
80             temp.flag=1;
81             s.push(temp);
82         }
83     }
84     return s.top().num;
85 }
86 int main() {
87     mp['+']=mp['-']=1;
88     mp['*']=mp['/']=2;
89     cin>>str;
90     while(!s.empty())s.pop();
91     change();
92     printf("%.2lf\n",cal());
93     return 0;
94 }

猜你喜欢

转载自www.cnblogs.com/aiqinger/p/12682734.html