为什么在后缀评估中尝试减法时不起作用?

Why isn't work when trying subtraction in postfix evaluation?

本文关键字:不起作用 后缀 评估 为什么      更新时间:2023-10-16

我正在尝试从后缀中获取结果。但是减法时给了我错了,不知道为什么。请为C ++新手提供许多帮助。

我从堆栈中得到了两个操作数。并尝试减去"上次弹出"-"第一次弹出"。

/*pf_exp is postfix expression. String type*/
for (int i=0; i<pf_exp.length(); i++)
{
int sub_result; // saving result.
if (48 <= (int)pf_exp[i] && (int)pf_exp[i] <= 57)
{
operands.push((int)pf_exp[i] - 48);
}
else
{
/*operators is a stack<int> from '#include<stack>' storing operands.*/
int operand2 = operands.top();
operands.pop();
int operand1 = operands.top();
operands.pop();
if(pf_exp[i] == '+')
{
sub_result = operand1 + operand2;
}
else if(pf_exp[i] == '-')
{
sub_result = operand1 - operand2;
}
else if(pf_exp[i] == '*')
{
sub_result = operand1 * operand2;
}
else if(pf_exp[i] == '/')
{
sub_result = operand1 / operand2;
}
operands.push(sub_result);
}
}

我预计"789--"的输出是"-10",但实际输出是"8"。

您可能将堆栈视为队列。您期望 (7 - 8) - 9 = -10,但是,由于您使用的是堆栈,因此返回最后添加的项目,因此正如 Ben 所写,您实际上是在执行 7 - (8 - 9) = 8。请改用队列,并更改操作数的顺序以获取实际想要的内容。

更新

抱歉,我的解释没有考虑后缀评估。正如注释所述,根据定义,它应始终使用堆栈。尽管如此,我的回答可能会解释,为什么你想错了结果。