问题描述
以下代码给出输出b = 0;
following code give output b = 0;
int b = 0;
b = b++;
b +=b;
System.out.println("Byte : "+b);
我的尝试:
What I have tried:
b = b++;
为什么b ++指定0不是1
why b++ assign 0 not 1
推荐答案
int x = 34;
int y = x ++;
x首先分配给y,然后加1。因此,x变为35而y被赋值为34.
int x = 34;
int y = x++;
x is first assigned to y and then incremented by one. Therefore, x becomes 35 while y is assigned with the value 34.
参考: []
现在,当你将增加后的值分配给同一个变量时,只需指定旧的值,即,以下行中的0到b-
Reference: Increment and Decrement Operators - Java Tutorial - Java With Us[^]
Now, when you assign the post-increamented value to the same variable it just assign the old value i.e, 0 to b in the following line-
b = b++; //b=0
所以你得到0作为输出。
将上面的行改为 -
So you are getting 0 as output.
Change the above line to just -
b++; //b=1
尝试以下代码 -
Try following code-
int b = 0;
b++; //changed line
//b +=b; // meaningless as it addsup to itself
System.out.println("Byte : "+b);
希望,我能澄清你的疑问。如果没有,请告诉我:))
Hope, I was able to clarify your doubt. If not, please let me know :)
这篇关于使用java增量出现问题,增量无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!