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?

huangapple go评论65阅读模式
英文:

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 &lt; 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.

huangapple
  • 本文由 发表于 2020年7月28日 20:52:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63134587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定