简体   繁体   English

初学java for-loop

[英]Beginner java for-loop

this code: 这段代码:

for(int i=5; i<50; i=i*2){ 
} 

Why does it loop 4 times instead of 3? 为什么它循环4次而不是3次? I thought it did 5x2 which = 10, then 10 x 2 which = 20, then 20 x 2 which = 40, and stops there since 40 x 2 is greater than 50. 我认为它做了5x2 = 10,然后10 x 2 = 20,然后20 x 2 = 40,并且因为40 x 2大于50而停在那里。

Print the numbers: 打印数字:

for (int i = 5; i < 50; i = i * 2) {
    System.out.println(i);
}

Output: 输出:

5
10
20
40

So you are missing the first iteration when i == 5 . 因此,当i == 5时,您缺少第一次迭代。

Incidentally, i = i * 2 can be written as i *= 2 . 顺便提及, i = i * 2可以写为i *= 2

The first execution uses the assigned value of i . 第一次执行使用i的指定值。 It only iterates after executing. 它只在执行后迭代。 So it will run once before the three times that you have listed. 所以它会在你列出的三次之前运行一次。

On the first iteration i is 5 . 在第一次迭代中, i5

The second time it loops, i is 10 . 它第二次循环, i10

The third time i is 20 . 第三次i20。

After the third iteration i is 40 . 在第三次迭代后, i 40岁 Has i passed 50 yet? i过了50岁了吗? No. 没有。

After the fourth iteration i is 80 , and we exit the loop. 在第四次迭代后, i80 ,然后我们退出循环。

That makes 4 iterations. 这使得4次迭代。

Well, the start: 好吧,开始:

if i < 50 --> do a iteration

i=5 --> less than 50 --> first loop; i=5 - >小于50 - >第一次循环;

Now the increment of i --> i = i*2 --> i = 5*2 = 10 现在增量i - > i = i*2 - > i = 5*2 = 10

i=10 --> less than 50 --> second loop; i=10 - >小于50 - >第二次循环;

Now the increment of i --> i = i*2 --> i = 10*2 = 20 现在增量i - > i = i*2 - > i = 10*2 = 20

i=20 --> less than 50 --> third loop; i=20 - >小于50 - >第三循环;

Now the increment of i --> i = i*2 --> i = 20*2 = 40 现在增量i - > i = i*2 - > i = 20*2 = 40

i=40 --> less than 50 --> fourth loop; i=40 - >小于50 - >第四循环;

Now the increment of i --> i = i*2 --> i = 40*2 = 80 现在增量i - > i = i*2 - > i = 40*2 = 80

i=80 --> bigger than 50 --> stop i=80 - >大于50 - >停止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM