a = a ++如何在java中工作
最近我遇到了这段Java代码:
int a=0; for(int i=0;i<100;i++) { a=a++; } System.out.println(a);
为’a’打印的值为0.但是在C的情况下,’a’的值为100。
在Java的情况下,我无法理解为什么值为0。
a = a++;
以递增a
开始,然后将a
恢复为旧值,因为a++
返回未递增的值。
简而言之,它在Java中没有任何作用。 如果要增加,只使用这样的后缀运算符:
a++;
a ++是一个后增量,因此a被赋值为a(总是0),并且a的ghost变量随后增加,对真实a没有任何影响,也没有保存结果。 因此,a始终分配为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