英文:
I saw this piece of code in a coding book and the output was 3, 5, 7, 9. Can someone explain to me why number 1 is not displayed in the output?
问题
以下是我在VS Code中尝试的代码:
int i = 1;
while (i < 10)
if ((i++) % 2 == 0)
System.out.println(i);
输出结果为:
3
5
7
9
英文:
Here is the code that I tried in VS Code:
int i = 1;
while (i < 10)
if((i++) % 2 == 0)
System.out.println(i);
And the output was:
3
5
7
9
答案1
得分: 0
在循环的第一次迭代中,i == 1。
i++ 将 i 增加到 2,但返回值为 1。
因此 if((i++) % 2 == 0) 的值为 false(因为 1 不是偶数),并且不会打印任何内容。
在下一次迭代中,i++ 将 i 增加到 3,但返回值为 2。
因此 if((i++) % 2 == 0) 的值为 true(因为 2 是偶数),并且会打印 3。
即使在循环的第一次迭代中将 i 打印出来,也不会打印 1,因为 i++ 会在 println 语句之前将 i 增加到 2。
英文:
At the first iteration of the loop i == 1.
i++ increments i to 2, but returns 1.
Therefore if((i++) % 2 == 0) evaluates to false (since 1 is not even), and nothing is printed.
In the next iteration, i++ increments i to 3, but returns 2.
Therefore if((i++) % 2 == 0) evaluates to true (since 2 is even), and 3 is printed.
1 would not be printed even if i was printed on the first iteration of the loop, since i++ increments i to 2 before the println statement.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论