栈计算逆波兰表达式

 1 #include<stack>
 2 #include<math.h>
 3 #include<iostream>
 4 #include<string.h>
 5 
 6 using namespace std;
 7 
 8 const char* s1 = "8 4 + 6 2 * -";
 9 const char* s2 = "2 3 5 + * 7 1 / + 4 -";
10 
11 float calculation(float i, char j, float k)
12 {
13     if ('!' == j)
14     {
15         float factorial = 1;
16         for (int a = 1; a <= i; ++a)
17         {
18             factorial *= a;
19         }
20         return factorial;
21     }
22     else if ('+' == j)
23     {
24         return k + i;
25     }
26     else if ('-' == j)
27     {
28         return k - i;
29     }
30     else if ('*' == j)
31     {
32         return k * i;
33     }
34     else if ('/' == j)
35     {
36         return k / i;
37     }
38     else if ('^' == j)
39     {
40         return pow(k, i);
41     }
42 }
43 
44 float calculationStr(const char* S)
45 {
46     stack<float> numStack;
47     for (int i = 0; i < strlen(S); ++i)
48     {
49         if(isalnum(S[i]))
50         {
51             string str = "";
52              while(isalnum(S[i]))
53              {    
54                  str += S[i++];    
55             } 
56             --i;
57             numStack.push(atof(str.c_str()));
58         }
59         else if(' ' != S[i] && '\0' != S[i])
60         {
61             if('!' == S[i])
62             {
63                 float num1 = numStack.top();
64                 numStack.pop();
65                 numStack.push(calculation(num1, S[i], 0));
66             }
67             else
68             {
69                 float num1 = numStack.top();
70                 numStack.pop();
71                 float num2 = numStack.top();
72                 numStack.pop();
73                 numStack.push(calculation(num1, S[i], num2));
74             }
75         }
76     }
77     return numStack.top();
78 } 
79 
80 int main()
81 {
82     cout<<calculationStr(s1)<<endl;
83     cout<<calculationStr(s2)<<endl;
84 }

 

posted @ 2021-02-23 19:21  梦涵的帅爸爸  阅读(65)  评论(0编辑  收藏  举报