[英]What does this Java for loop termination condition mean?
I am wondering if anyone here knows what the termination condition in the following for loop is supposed to mean. 我想知道这里是否有人知道以下for循环的终止条件应该是什么意思。
for (int i = 0; i < 1 << Level; i++) {
...
}
<<
shifts the bits of the first operand n
times to the left, where n
is the second operand. <<
将第一个操作数的位向左移位n
次,其中n
是第二个操作数。
Therefore 1 << Level
shifts the single 1
bit of the number 1
Level
times to the left, which is equivalent to calculating 2 ^ Level. 因此, 1 << Level
将数字1
Level
的单个1
位向左移动,这相当于计算2 ^ Level。
So i < 1 << Level
is equivalent to i < Math.pow(2,Level)
. 所以i < 1 << Level
相当于i < Math.pow(2,Level)
。
Simply stated 简单地说
for (int i = 0; i < 1 << Level; i++) {
...
}
is equal to 等于
for (int i = 0; i < Math.pow(2,Level); i++) {
...
}
So the for loop will run for "Math.pow(2,Level)" times since you are counting from 0 to Math.pow(2,Level)-1. 所以for循环将运行“Math.pow(2,Level)”次,因为你从0计算到Math.pow(2,Level)-1。
if Level = 2 then the loop is 如果Level = 2则循环为
for(int i =0;i<4;i++){}
if Level = 3 then the loop is 如果Level = 3则循环为
for(int i =0;i<8;i++){}
if Level = 5 then the loop is 如果Level = 5则循环为
for(int i =0;i<32;i++){}
In addition to the other answers it might help putting parenthesis around the expression if that is unclear 除了其他答案之外,如果不清楚,可能有助于在表达式周围加上括号
for (int i = 0; i < (1 << Level); i++) {
...
}
Also since Level
is a variable it is suggested to have a small letter ie level
unless it is a constant, then it should be LEVEL
. 此外,由于Level
是一个变量,因此建议使用一个小写字母即level
除非它是一个常数,那么它应该是LEVEL
。 And I think in general that readability > performance (if it is even a problem?). 我认为一般来说可读性>性能(如果它甚至是一个问题?)。 So Math.pow(2,Level)
is much more easy to understand if you are not a low level programmer, looks much more like Java than C. 因此Math.pow(2,Level)
如果您不是低级程序员, Math.pow(2,Level)
更容易理解,看起来更像Java而不是C.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.