关于逆波兰式的c++实现

正常的表达式 逆波兰表达式
a+b ---> a,b,+
a+(b-c) ---> a,b,c,-,+
a+(b-c)*d ---> a,b,c,-,d,*,+
a+d*(b-c)--->a,d,b,c,-,*,+
a=1+3 ---> a=1,3 +
 
代码运算如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include "iostream"
#include "string"
#include "stack"
using namespace std;
 
int main()
{
    string str;
    stack<int> sk;
    int s = 0, l = 0, r = 0;
    cout << "请输入逆波兰公式:" << endl;
    while (cin>>str)
    {
        if (str[0] == '#')
        {
            break;
        }          
        //如果第一个是0-9数字则转换为数字压栈
        else if (isdigit(str[0]))
        {
            sk.push(atoi(str.c_str()));
        }
        else
        {
            l = sk.top();
            sk.pop();
            r = sk.top();
            sk.pop();
            switch (str[0])
            {
            case '+':
                s = r + l;
                break;
            case '-':
                s = r - l;
                break;
            case '*':
                s = r * l;
                break;
            case '/':
                s = r / l;
                break;
            }
            //把计算的结果再次压栈
            sk.push(s);
        }
         
    }
    cout << "结果为:" << s << endl;
    system("pause");
    return 0;
}

  

posted @   zhou_blog  阅读(2938)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示