For what value of i does while (i == i + 1) {} loop forever?

I ran cross this puzzler from an advanced programming course at a UK university exam.

Consider the following loop, in which i is, so far, undeclared:

while (i == i + 1) {}

Find the definition of i, that precedes this loop, such that the while loop continues for ever.

The next question, which asked the same question for this code snippet:

while (i != i) {}

was obvious to me. Of course in this other situation it is NaN but I am really stuck on the prior one. Does this have to do with overflow? What would cause such a loop to loop for ever in Java?

10015 次浏览

首先,由于 while (i == i + 1) {}循环不会改变 i的值,使这个循环无限等价于选择一个满足 i == i + 1i值。

这样的价值观有很多:

让我们从“异国情调的”开始:

double i = Double.POSITIVE_INFINITY;

或者

double i =  Double.NEGATIVE_INFINITY;

The reason for these values satisfying i == i + 1 is stated in
JLS 15.18.2. 数字类型的加法运算符(+ 和 -) :

无穷大和有限值的和等于无穷操作数。

这并不奇怪,因为将有限值加到无限值中应该会得到无限值。

也就是说,大多数满足 i == i + 1i值只是大的 double(或 float)值:

For example:

double i = Double.MAX_VALUE;

或者

double i = 1000000000000000000.0;

或者

float i = 1000000000000000000.0f;

doublefloat类型的精度有限,因此如果取足够大的 doublefloat值,将 1添加到它将导致相同的值。

这些谜题在 Joshua Bloch 和 Neal Gafter 的《 Java 谜题: 陷阱、陷阱和角落案例》一书中有详细描述。

double i = Double.POSITIVE_INFINITY;
while (i == i + 1) {}

或:

double i = 1.0e40;
while (i == i + 1) {}

两者都会导致一个无限循环,因为将 1添加到一个足够大的浮点值不会改变这个值,因为它不会“架起缺口”到它的继任者 1

关于第二个谜题的注释(给未来的读者) :

double i = Double.NaN;
while (i != i) {}

also results in an infinite loop, because NaN 不等于任何浮点值,包括它本身 < sup > 2 .


1-Java 智力游戏: 陷阱、陷阱和角落案例(第4章-糊涂智力游戏)。

2-JLS 15.21.1

只是一个想法: 布尔型怎么样?

bool i = TRUE;

这不是 i + 1 == i的案子吗?

double i = Double.POSITIVE_INFINITY;