在我的反向波蘭符號計算器上執行兩個數字的減法時,我得到一個負數結果,例如:20 5 - = -15然而,我希望看到15。任何人都可以看到我的代碼出錯的地方嗎? else if (input.equals("-")) { int n1 = stack.pop(); int n2 = stack.pop(); int result = n1 - n2; stack.push((int)result); }
2 回答

精慕HU
TA貢獻1845條經驗 獲得超8個贊
堆棧的原理是LIFO(最后一個進先出)。
因此,當您第一次推送然后推送到堆棧中時,第一個將返回,第二個將返回。因此,您計算而不是 .205pop5pop205 - 2020 - 5
您應該反轉操作數的順序以進行正確的計算:
else if (input.equals("-")) {
int n1 = stack.pop();
int n2 = stack.pop();
int result = n2 - n1;
stack.push((int)result);
}
添加回答
舉報
0/150
提交
取消