后缀计算器给我错误的答案

时间:2013-11-03 03:06:49

标签: java calculator postfix-notation

我似乎无法弄清楚为什么我的后缀计算器得到了错误的答案。

我的代码是:

public static int calcRPN(String[] postfix)
{
    Stack<Integer> st = new Stack<Integer>();
    String value;
    int ans = 0;

    for(int i = 0; i < postfix.length; i++){
       value = postfix[i];

       if      (value.equals("+")) ans = st.push(st.pop() + st.pop());
       else if (value.equals("-")) ans = st.push(st.pop() - st.pop());
       else if (value.equals("*")) ans = st.push(st.pop() * st.pop());
       else if (value.equals("/")) ans = st.push(st.pop() / st.pop());
       else st.push(Integer.valueOf(value));
    }

    return ans;
}

输出:

Postfix: [4, 5, 7, 2, +, -, *], Answer: -16, Your answer: 16 ==> NO match...
Postfix: [3, 4, +, 2, *, 7, /], Answer: 2, Your answer: 0 ==> NO match...
Postfix: [5, 7, +, 6, 2, -, *], Answer: 48, Your answer: -48 ==> NO match...
Postfix: [4, 2, 3, 5, 1, -, +, *, +], Answer: 18, Your answer: 2 ==> NO match...
Postfix: [2, 3, *, 10, 4, /, -], Answer: 4, Your answer: -6 ==> NO match...
Postfix: [4, 23, 12, -, 2, *, +], Answer: 26, Your answer: -18 ==> NO match...

答案显然应该匹配。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

提示1:某些操作(例如/-commutative property

  

在数学中,如果改变操作数的顺序而不是改变结果,则二进制操作是可交换的。

提示2:push(a); push(b); x = pop(); y = pop之后,a,b,x和y如何关联?

答案 1 :(得分:2)

你的代码的问题是你已经颠倒了操作数的顺序。 虽然这对于+和*无关紧要, 对于/和 - 很重要。 请参阅:http://www.youtube.com/watch?v=uh7fD8WiT28

Input  Stack(Actual)  Ans(Actual)  Stack(Ur Code)  Ans(ur Code)
  1       1              0            1               0
  2       12             0            12              0
  -       pop()          1-2          pop()x2         2-1=1

您的代码的另一个问题如下: 请注意,使用整数堆栈并不能保证结果为整数。在某些情况下,由于在进行分割时丢失信息,这可能会给您带来麻烦。另外,您必须将答案推回到堆栈中,因此堆栈也需要是浮点数。 所以你需要为堆栈和答案使用浮点。

Ex: 2/3 results to 0
((2/3)*3) = > 23/3*
Input Stack
2     2
3     2 3
/     2 3 / =>ans=0
3     0 3
*     0 3 * =>ans=0
/*Wrong Output*/
相关问题