美文网首页
后缀表达式求值

后缀表达式求值

作者: HelloSam | 来源:发表于2020-03-14 08:59 被阅读0次
#include<iostream>
#include<string>
#include<stack>
#include<cstdio>
using namespace std;

int op(int a, int b, char ch)
{
    if (ch == '+') return b + a; //注意运算顺序
    if (ch == '-') return b - a;
    if (ch == '*') return b * a;
    if (ch == '/') return b / a;
}

//后缀表达式求值‘0’——‘9’是48-57
int main()
{
    string str;
    cin >> str;
    stack<char> vc;
    int ret;
    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] >= 48 && str[i] <= 57)//是数字
        {
            vc.push(str[i]);
        }
        else
        {
            int tempa = vc.top() - '0'; vc.pop();
            int tempb = vc.top() - '0'; vc.pop();
            ret = op(tempa, tempb, str[i]);
            vc.push(ret+'0');
        }

    }
    cout << vc.top() - '0' << endl;

    return 0;
}

输入:123*+42/-(即是中缀表达式的1+2*3-4/2)
输出:5

相关文章

网友评论

      本文标题:后缀表达式求值

      本文链接:https://www.haomeiwen.com/subject/avxmshtx.html