Reverse Polish Notation Calc: subtraction of two positive numbers returning a minus?

问题: When performing a subtraction of two number on my Reverse Polish Notation Calculator, I get a minus number result, for example: 20 5 - = -15 Whereas, I would expect to...

问题:

When performing a subtraction of two number on my Reverse Polish Notation Calculator, I get a minus number result, for example:

20 5 - = -15

Whereas, I would expect to see 15.

Can anyone see where I am going wrong with my code?

   else if (input.equals("-")) {
            int n1 = stack.pop();
            int n2 = stack.pop();
            int result = n1 - n2;

            stack.push((int)result);
        }

回答1:

The principle of a stack is LIFO (Last In First Out).

Therefore, when you first push 20 and then push 5 into the stack, the first pop will return 5 and the second pop will return 20. Therefore you calculate 5 - 20 instead of 20 - 5.

You should reverse the order of the operands in order to make the correct computation:

else if (input.equals("-")) {
    int n1 = stack.pop();
    int n2 = stack.pop();
    int result = n2 - n1;
    stack.push((int)result);
}

回答2:

You're popping 5 and then 20. I.e., you need to reverse the order of subtraction:

int result = n2 - n1;
  • 发表于 2019-03-26 17:20
  • 阅读 ( 167 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除