简体   繁体   English

for循环的迭代次数

[英]The number of iterations of a for-loop

I can't figure out for the following for-loop, how many time it will execute?我无法弄清楚以下 for 循环,它将执行多少次? It seems to me that it will never stop running as i will never be less than 0. But I know that i is an int , so I'm quite confused about when the loop will stop.在我看来,它永远不会停止运行,因为i永远不会小于 0。但我知道i是一个int ,所以我对循环何时停止感到很困惑。 Many thanks for your help!非常感谢您的帮助!

for (int i = n; i > 0; i = i/2) {
    System.out.println(s);
}

Also is the complexity log2(n) ?复杂性也是log2(n)吗?

It depends.这取决于。

For n <= 0 it will be never inside.对于n <= 0它永远不会在里面。

For n > 0 it will be executed log2(n) + 1 times对于n > 0将执行log2(n) + 1


n = 8

It will be invoked for i = 8, 4, 2, 1 so finally, 3 + 1 = log2(8) + 1它将被调用i = 8, 4, 2, 1所以最后, 3 + 1 = log2(8) + 1


It also works with @Keppil test:它也适用于@Keppil 测试:

30 < log2(2147483648 - 1) < 31

and the result set has 31 elements.结果集有 31 个元素。

It will run for a number of iterations,given by log2(n) , the last one being when i=1.它将运行多次迭代,由log2(n) 给出,最后一次是当 i=1 时。 When the condition is checked the next time, i = 1/2 in int, which evaluates to zero and violates the condition and exits the loop.下次检查条件时,int 中的 i = 1/2,计算结果为零并违反条件并退出循环。 So it depends on the value of n .所以这取决于n的值。

Just modify your code a little bit to see what happens there:只需稍微修改您的代码,看看那里会发生什么:

int n = 50;
for (int i=n; i>0; i=i/2){
    System.out.println("i: " + i);
}
System.out.println("1/2 in Java is: " + 1/2);

The output is:输出是:

i: 50
i: 25
i: 12
i: 6
i: 3
i: 1
1/2 in java is: 0

Now you should be able to understand why this loop ends.现在您应该能够理解为什么这个循环结束了。

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

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