学习 For 和 While 循环,我对这段代码的输出感到困惑。

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

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.

huangapple
  • 本文由 发表于 2020年9月16日 00:44:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63906375.html
匿名

发表评论

匿名网友

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

确定