[英]Why doesn't the increment operator change the value of variable in java?
I recently wrote snippet code like this 我最近写了这样的代码段
public class TestIncrement {
public static void main(String[] args){
double a = 12.4;
double b = 5.6;
a -=b -=b -= b -= b -= b -= b;
System.out.println(a);
a-=b;
System.out.println(a);
}
}
and the output is: 输出为:
12.4
12.4
Why increment operator not work? 为什么增量运算符不起作用?
-=
and all other assignment operators are right-associative. -=
和所有其他赋值运算符都是右关联的。 This line: 这行:
a -=b -=b -= b -= b -= b -= b;
doesn't mean "decrease a
by the value of b
6 times". 并不意味着“减少
a
由的值b
6次”。 It means the same as this: 它的含义与此相同:
a -= (b -= (b -= (b -= (b -= (b -= b)))));
which means "decrease b
by the value of b
, then decrease b
by the new value of b
, then do that 3 more times, then decrease a
by the final value of b
". 这意味着“降低
b
通过的值b
,则减少b
通过的新值b
,则这样做3次以上,则减少a
通过的最终值b
”。 b
is 0 after the first -=
, so the rest of the statement does nothing, as does the b
在第一个-=
之后为0,因此语句的其余部分不执行任何操作,就像
a-=b;
line. 线。
It does work. 确实有效。 Your
b
variable is equal to 0. 您的
b
变量等于0。
If I put parentheses around all that to make it easier to understand, we get this: 如果在所有内容之间加上括号以使其更易于理解,我们将得到:
public class TestIncrement {
public static void main(String[] args){
double a = 12.4;
double b = 5.6;
a -= (b -= (b -= (b -= (b -= (b -= b)))));
System.out.println(a);
a -= b;
System.out.println(a);
}
}
The first b -= b
statement sets b
to 0
. 第一个
b -= b
语句将b
设置为0
。 After 0
is subtracted from b
4 more times, the result is still 0
, which obviously leaves the value of a
unchanged. 后
0
从减去b
4次以上,结果仍然是0
,这显然离开的值a
不变。 Even if you try again, in the a -= b
line, you will still get the same result: 12.4 − 0.0 = 12.4
. 即使再次尝试,在
a -= b
行中,您仍然会得到相同的结果: 12.4 − 0.0 = 12.4
。
You could have figured this out on your own, by writing a simpler example. 通过编写一个更简单的示例,您可以自己解决这个问题。
public static void main(String[] args){
int a = 1;
int b = 2;
int c = 3;
a -= b -= c;
System.out.println(a + " " + b + " " + c);
}
You'd be surprised to see that the output is 2 -1 3
您会惊讶地看到输出为
2 -1 3
This reason is, the above code is equal to: 原因是,上面的代码等于:
public static void main(String[] args){
int a = 1;
int b = 2;
int c = 3;
b -= c;
a -= b;
System.out.println(a + " " + b + " " + c);
}
Don't do spaghetti code. 不要做意大利面条代码。 :(
:(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.