为什么 post 递增运算符在此代码中递增 'a' 失败?
Why post increment opertor failed to increment 'a' in this code?
package com;
public class Test {
public static void main(String[] args)
{
int a= 11, b = 10;
a = a++ + ++b; //why? output is "22 11" and not "23 11"
System.out.println(a+" "+b);
}
}
表达式的计算方式如下(大致上,我没有检查 JLS 的计算顺序,但我认为它是从左到右):
a = a++ + ++b; // a is 11, b is 10
a = 11 + ++b; // a is 12 but its previous value 11 was returned by a++, b is 10
a = 11 + 11; // a is 12, b is 11 and its updated value was returned by ++b
a = 22; // a is 12, b is 11 and its updated value was returned by ++b
因此,这是预期的结果,您只需应用这些运算符的定义即可。
a++ 表示 "a" 在您编写它并在之后更改它的地方具有旧值。 ++a 表示 "a" 在第一个变化值之后将被计算。
So:
a = 5;
b = 5;
So:
a++ + ++b = (5 (and a + 1 later) + (at first b + 1) 6.
希望你能理解我)我的英语和你的水平差不多Java=)
package com;
public class Test {
public static void main(String[] args)
{
int a= 11, b = 10;
a = a++ + ++b; //why? output is "22 11" and not "23 11"
System.out.println(a+" "+b);
}
}
表达式的计算方式如下(大致上,我没有检查 JLS 的计算顺序,但我认为它是从左到右):
a = a++ + ++b; // a is 11, b is 10
a = 11 + ++b; // a is 12 but its previous value 11 was returned by a++, b is 10
a = 11 + 11; // a is 12, b is 11 and its updated value was returned by ++b
a = 22; // a is 12, b is 11 and its updated value was returned by ++b
因此,这是预期的结果,您只需应用这些运算符的定义即可。
a++ 表示 "a" 在您编写它并在之后更改它的地方具有旧值。 ++a 表示 "a" 在第一个变化值之后将被计算。
So:
a = 5;
b = 5;
So:
a++ + ++b = (5 (and a + 1 later) + (at first b + 1) 6.
希望你能理解我)我的英语和你的水平差不多Java=)