为什么“--i”和 "i--" 在 Java for 循环中具有相同的行为?

Why do "--i" and "i--" have the same behavior in a Java for loop?

为什么在 Java 中,i----i循环 ?

例如: 我的变量 "i" 在循环之前没有减少:

for(int i = 5; i > 0; --i) {
    System.out.println(i);
}

for(int i = 5; i > 0; i--) {
    System.out.println(i);
}

... 都会打印 5,4,3,2,1.

但是这个:

int i = 5;
System.out.println(--i);


int i = 5;
System.out.println(i--);

...将打印 4 和 5。

这是因为for循环是这样的:

for (<1. variable declaration and initialization>;
     <2. condition to loop>;
     <4. for update>) {
    <3. statements>
}

您的i----i 条件在for 循环中的语句执行之后和检查要循环的条件之前执行。这意味着,在 for update 部分使用 i----i 并不重要。

--ii-- 都有相同的副作用,i 减一。它们的结果值不同。在循环代码中,您只使用了副作用,忽略了结果。在独立的 println 代码中,您正在显示结果。

For 循环是这样工作的:

for(<Part that will be executed before the loop>;
    <Part that is the condition of the loop>;
    <Part that will be executed at the end of each iteration) {
    <statements>
}

任何for循环都可以这样重写:

<Part that will be executed before the loop>
while(<Part that is the condition of the loop>) {
    <statements>
    <Part that will be executed at the end of each iteration>
}

使用您的示例执行此操作会导致:

int i = 5; // Part that will be executed before the loop
while(i > 0) { // Part that is the condition of the loop
    System.out.println(i); // statements
    --i; // Part that will be executed at the end of each iteration
}

如您所见,输出是 --i 还是 i-- 并不重要,因为打印调用总是在变量递减之前发生。为了达到你想要的结果,你可以试试这个:

int i = 5;
while(i > 0) {
    --i;
    System.out.println(i);
}

我认为最简单的表达方式是,在循环中,您打印如下:

System.out.println(i);

注意 println() 的参数是 "i",而不是 "i--" 或“--i”。减少已经发生在其他地方。您不是在打印递减的结果,而是在循环中打印 "i" 的值。