我在 Java 编程测验问题之一中发现了这一点。
public class Calculator {
public static void main(String[] args) {
int i = 0;
Calculator c = new Calculator();
System.out.print(i++ + c.opearation(i));
System.out.print(i);
}
public int operation(int i) {
System.out.print(i++);
return i;
}
}
执行上面的代码片段会得到121
的结果。我预计它是 111
。我将解释我是如何解释它的。
+
加法运算符将从右向左执行(引用: operator precedence )。因此,首先调用 c.operation(0)
并打印值 1
而我预计该值为 0
因为 System.out.print
首先打印 i
的值,然后递增 i 值,因为它是后递增运算符。
其次,i
值 1 返回到 main,并且语句 System.out.print(i++ + 1)
现在被执行。由于 i
具有后增量运算符,因此它应该像 0 + 1
一样执行并生成结果 1
并将其打印结果为 2
.
第三,i
值现在增加到 1
,并且按预期打印。
简而言之,我希望将值打印为 011
,但我得到的结果为 121
。我不确定我的解释哪里出了问题。
最佳答案
<小时/>The additive operators have the same precedence and are syntactically left-associative (they group left-to-right).
int i = 0;
System.out.print(i++ + c.operation(i));
计算
i++
,得到左操作数0
,并将i
增加到1
。将
i(1)
传递给c.operation(i)
,执行System.out.print(i++)
。 打印1
,然后返回2
(右操作数)。i++ + c.operation(i) ---> 0 + 2
,打印2
。打印
1
。
关于java - 以下代码片段不会产生预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51970225/