后期修复表达式解算器

Post-fix expression solver

本文关键字:表达式      更新时间:2023-10-16

目标是编写一个程序来解决修复后/反向波兰表示法表达式。这似乎是一项简单的任务,但我似乎忽略了其中的错误。提前感谢您的帮助。

vector<int> stack;
string input;
cout << "Please enter post-fix expression to be evaluated (+, -, *, /): ";
cin >> input;
for(int i=0; i<input.size(); i++)
{
    if(input[i] == '+')
    {
        int temp1 = stack.back();
        stack.pop_back();
        int temp2 = stack.back();
        stack.pop_back();
        int sum = temp1 + temp2;
        stack.push_back(sum);
    }
    else if(input[i] == '-')
    {
        int temp1 = stack.back();
        stack.pop_back();
        int temp2 = stack.back();
        stack.pop_back();
        int difference = temp1 - temp2;
        stack.push_back(difference);
    }
    else if(input[i] == '*')
    {
        int temp1 = stack.back();
        stack.pop_back();
        int temp2 = stack.back();
        stack.pop_back();
        int product = temp1 * temp2;
        stack.push_back(product);
    }
    else if(input[i] == '/')
    {
        int temp1 = stack.back();
        stack.pop_back();
        int temp2 = stack.back();
        stack.pop_back();
        int quotient = temp1 / temp2;
        stack.push_back(quotient);
    }
    else
    {
        stack.push_back(input[i]);
    }
}
cout << "Result: " << stack.back();

真正的问题是stack.push_back(input[i]);您推回一个char,例如'7',这将导致55被推到堆栈上。