为什么在后缀评估中尝试减法时不起作用?
Why isn't work when trying subtraction in postfix evaluation?
我正在尝试从后缀中获取结果。但是减法时给了我错了,不知道为什么。请为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。请改用队列,并更改操作数的顺序以获取实际想要的内容。
更新
抱歉,我的解释没有考虑后缀评估。正如注释所述,根据定义,它应始终使用堆栈。尽管如此,我的回答可能会解释,为什么你想错了结果。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 在qt QFileDialog中设置后缀在linux中不起作用,如何解决?
- 组合"%"和可选后缀时,自动属性传播有时不起作用
- 中缀到后缀 - 优先级不起作用
- 为什么在后缀评估中尝试减法时不起作用?
- 中缀到后缀表达式转换代码不起作用
- 后缀 ($') 在 C++ 中不起作用regex_replace
- 重载后缀运算符不起作用