class T {
public static void main(String args[]) {
int x = 0;
x = x++;
System.out.println(x);
}
}
class T {
public static void main(String args[]) {
int x = 0;
x = x++;
System.out.println(x);
}
}
++
是“后增量”运算符 - 它返回变量在递增之前的值。因为后缀自增运算符返回一个临时值(x
的当前值),然后再对x进行递增操作。
可以这样尝试:
class T {
public static void main(String args[]) {
int x = 0;
x = ++x;
System.out.println(x);
}
}
x++
,不需要加上 x =
部分。 :) - Danicax = x++;
等同于
temp = x;
x = x + 1;
x = temp;
这就是为什么输出为零。
这个操作符被称为后自增操作符。另一个与后自增相关的操作符是前自增操作符。
x = ++x;
++
运算符,这意味着在赋值之后才进行计算。因此首先计算x = x
,所以x
保持为0
,然后计算x++
,但结果没有被分配给任何变量。++
运算符来实现你想要的结果:x = ++x;
从文档中得知:
增量/减量运算符可以应用于操作数之前(前缀)或之后(后缀)。代码result++;和++result;最终都会使result增加一。唯一的区别是前缀版本(++result)计算为递增值,而后缀版本(result++)计算为原始值。
x++
返回零,然后增加 x。赋值 x = x++
将 x
(在它被增加之后)设置为 x++
的返回值,即 0。
因为++在后面是程序运行后再加,以下两种方式可以修复它
class T {
public static void main(String args[]) {
int x = 0;
x = ++x;
System.out.println(x);
}
}
或者
class T {
public static void main(String args[]) {
int x = 0;
x += 1;
System.out.println(x);
}
}
我不确定这样做会对输出结果有所影响,但您并不需要导入并且可以更改:
x = x++;
至:
x++;
展示使用常规增量的后增量示例,正如之前的回答者所说:
class T {
public static void main(String args[]) {
for (int i = 0; i < 6; i++) {
int x = 0;
x = x+1+i;
System.out.println(x);
}
}
}
你正在做什么的解释:
class T {
public static void main(String args[]) {
int x = 0; // x is zero
x = x++; // assign x to be x (which is 0).
// then increment a non-existant variable by 1
System.out.println(x); //print 0
}
}
这是因为x++
实际上意味着“使用存储在x
中的值,然后将其递增”。如果您想在使用它之前递增该值,请改用++x
。
++x
。 - G_H