英文:
Learning For and While Loops and I'm confused about the output of this code
问题
int index = 1, balance = 1000;
while (index % 2 == 1)
{
balance -= index;
index = index * 2 + 1;
}
System.out.println(balance);
我不明白这段代码的输出为什么是1033。这段代码会如何结束呢?
这段代码怎么可能结束呢。条件似乎总是会被满足。任何帮助将不胜感激。谢谢。
英文:
int index = 1, balance = 1000;
while (index % 2 == 1)
{
balance -= index;
index = index * 2 + 1;
}
System.out.println(balance);
I don't understand how the output of this is 1033. How would the code end?
How would the code even end. It seems like the condition will always be fulfilled. Any help is appreciated. Thanks.
答案1
得分: 1
在Java中,index % 2
在正奇数时返回1,在负奇数时返回-1。
如果您不断将index
加倍,很快它会溢出,然后变为负数。在那时,index % 2 == 1
将不再成立。
英文:
In Java index % 2
returns 1 for positive odd numbers, and -1 for negative odd numbers.
If you keep doubling index
, pretty soon it will overflow, and then it will become negative. At that point index % 2 == 1
will no longer be true.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论