修复后表达式求解器

时间:2014-10-20 22:20:12

标签: c++

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

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();

1 个答案:

答案 0 :(得分:1)

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