前缀和后缀增量

Pre and Postfix Increment

a = 1;
int a2 = a++;
System.out.println("----------Test 3 ----------");
System.out.println("The value of a is " + a);
System.out.println("The value of a2 is " + a2);
System.out.println("The value of a2 is " + a2);

结果是:

----------Test 3 ----------

The value of a is 3

The value of a2 is 2

The value of a2 is 2

不明白为什么第二次输出后a2的值没有增加。甚至 a 使用后缀增量增加并分配给 a2。请给我解释一下。

前缀和后缀增量仅在您正在执行的语句中起作用。尝试在打印语句中添加前缀和后缀增量。

这就是 post 增量运算符设计的工作方式...

正在做

int a2 = a++;

相当于做

int a2 = a;
a = a + 1;

因此您的代码正在生成此输出:

----------Test 3 ----------
The value of a is 2
The value of a2 is 1
The value of a2 is 1

I don't understand why the value of a2 does not increase after the second output even a is increased using postfix increment and assigned to a2.

让我们一步步来:

a = 1

设置变量a为1;现在:

int a2 = a++;

将等同于:

int a2 = a;
a++;

首先赋值,然后递增,因此输出:

The value of a is 2
The value of a2 is 1
The value of a2 is 1

和名字post修复增量。

对于您想要的行为,请改用 ++a,即:

int a = 1;
int a2 = ++a;
System.out.println("The value of a is " + a);
System.out.println("The value of a2 is " + a2);
System.out.println("The value of a2 is " + a2);

输出:

The value of a is 2
The value of a2 is 2
The value of a2 is 2

在这种情况下:

int a2 = ++a; 等同于:

 a++;
 int a2 = a;