栈ADT应用:中缀表达式求值

栈ADT应用:中缀表达式求值

表达式求值是进行数据处理的最基本操作。请编写程序完成一个简单算术表达式的求值。要求如下: 

(1) 运算符包括:+、-、*、-、^(乘方)、括号

(2)运算量为数值常量,根据自己的能力可以对运算量做不同的约束,例如1位整数、多位整数、实数等(会有不同的测试用例);

输入:一行,即表达式,以“=”结束。例如:

           5*(8-3)+6/5=

输出:一行,即表达式的值。结果值为整数时输出为整数,如果有小数时保留5位小数。

           26.20000

例如:

输入 Result
5+(3-1)/2=
6

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int pre(char c)
 4 {
 5     if(c=='=')
 6         return 0;
 7     else if(c=='+'||c=='-')
 8         return 1;
 9     else if(c=='*'||c=='/')
10         return 2;
11     else if(c=='^')
12         return 3;
13     return 0;
14 }
15 void answer(stack<double> &num,stack<char> &op)
16 {
17     double b=num.top();
18     num.pop();
19     double a=num.top();
20     num.pop();
21     switch(op.top())
22     {
23     case '+':
24         num.push(a+b);
25         break;
26     case '-':
27         num.push(a-b);
28         break;
29     case '*':
30         num.push(a*b);
31         break;
32     case '/':
33         num.push(a/b);
34         break;
35     case '^':
36         num.push(pow(a,b));
37         break;
38     }
39     op.pop();
40 }
41 int main()
42 {
43     stack<double> num;
44     stack<char> op;
45     char s[1005];
46     scanf("%s",s);
47     for(int i=0; s[i]!='\0'; i++)
48     {
49         if(isdigit(s[i]))
50         {
51             double temp=atof(&s[i]);
52             num.push(temp);
53             while(isdigit(s[i])||s[i]=='.')
54                 i++;
55             i--;
56         }
57         else
58         {
59             if(s[i]=='(')
60                 op.push(s[i]);
61             else if(s[i]==')')
62             {
63                 while(op.top()!='(')
64                     answer(num,op);
65                 op.pop();
66             }
67             else if(op.empty()||pre(s[i])>pre(op.top()))
68                 op.push(s[i]);
69 
70             else if(!op.empty()&&pre(s[i])<=pre(op.top()))
71             {
72                 while(!op.empty()&&pre(s[i])<=pre(op.top()))
73                     answer(num,op);
74                 op.push(s[i]);
75             }
76         }
77     }
78     double ans=num.top();
79     if((ans-(int)ans)<0.001)
80         printf("%d",(int)ans);
81     else
82         printf("%.5f",ans);
83     num.pop();
84     op.pop();
85     return 0;
86 }

猜你喜欢

转载自www.cnblogs.com/sylvia1111/p/12654411.html