Puzzle 29: The Bride of a revolving person
Please provide a declaration of I that transforms the following loop into an infinite loop:
while (i! = i)
{
}
FAQ 29: The Bride of a revolving person
This cycle may be more confusing than the previous one. No matter what statements are made before it, it does seem that it should terminate immediately. A number is always equal to itself, isn't it?
Yes, but IEEE 754 floating-point arithmetic retains a special value to represent a number that is not a number. This value is the abbreviation for Nan ("not a number"), which is the value for all floating-point calculations that do not have a good numeric definition, such as 0.0/0.0. The specification describes the word,nan is not equal to any floating-point value, including itself[C # Language Specification 7.9.2]. Therefore, if I is initialized to Nan before the loop begins, then the terminating condition Test (i! = i) evaluates to true, and the loop never terminates. It's strange, but it's true.
I can be initialized with any floating-point arithmetic expression that evaluates to Nan, for example:
Double i = 0.0/0.0;
Similarly, for clarity, you can use the constants provided by the standard class library:
Double i = double. NaN;
There are other amazing places to Nan.any floating-point operation, as long as one or more of its number is Nan, the result is Nan[C # Language Specification 4.1.6]. This rule is very reasonable, but it has a strange result. For example, the following program will print false:
Class Puzzlers29
{
static void Main ()
{
Double i = 0.0/0.0;
System.Console.WriteLine (I-i = = 0);
}
}
The rules for this Nan rule are based on the following principles:once a computation has produced Nan, it is corrupted, and no further calculations can be made to repair such damage. The Nan value intentionally causes the damaged calculation to continue until it reaches a convenient place to handle the situation.
In summary, both the float and double types have a special Nan value, which is used to denote a number that is not a number. The rules for calculations involving Nan values are simple and sensible, but the results of these rules can be counterintuitive.
Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.
C # 29: The Bride of a revolving person