【发布时间】:2019-03-30 05:29:57
【问题描述】:
我正在尝试从后缀中获取结果。但是减法时它给了我错误,不知道为什么。请多多帮助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”。
【问题讨论】:
-
你为什么期望
-10来自(7 - (8 - 9))? -
- 和 / 的操作数以“错误”的顺序从堆栈中脱落。您必须对此进行补偿。
-
@BenVoigt
789--不是指7-8-9吗?我想把中缀改成后缀有错吗? -
不,在 RPN 中写
(7-8)-9是78-9- -
@BenVoigt 哦天哪……我是个傻瓜……
标签: c++ expression expression-evaluation