1

最近我遇到了这段Java代码:

int a=0;
for(int i=0;i<100;i++)
{
    a=a++;
}
System.out.println(a);

'a' 打印的值是 0。但是在 C 的情况下,'a' 的值是 100。

我无法理解为什么 Java 的值为 0。

4

3 回答 3

12
a = a++;

以递增开始a,然后恢复a为旧值,a++返回未递增的值。

简而言之,它在 Java 中什么也不做。如果要递增,请仅使用后缀运算符,如下所示:

a++;
于 2013-05-01T17:28:57.230 回答
0

a++ 是后自增,因此 a 被赋值为 a(始终为 0),a 的 ghost 变量随后自增,与真正的 a 没有区别,也不保存结果。结果,a 总是被赋值为 0,因此代码什么也不做

于 2013-05-01T17:34:47.533 回答
0

因为:

a = a++;///will assign 'a' to 'a' then increment 'a' in the next step , but from the first step 'a' is '0' and so on

要获得 100,您可以这样做:

a = ++a;////here the 'a' will be increment first then will assign this value to a so a will increment in every step 

或者

a++;////here the increment is the only operation will do here 
于 2013-05-01T17:39:40.247 回答