Puzzle 29: The Bride of the loop
Please provide a Statement on I to convert the following loop into an infinite loop:
While (I! = I)
{
}
Confused 29: The Bride of the loop
This loop may be more confusing than the previous one. No matter what statements are made before it, it seems that it should be terminated immediately. A number is always equal to itself, right?
Yes, but IEEE 754 Floating Point Arithmetic reserves a special value to indicate a number that is not a number. This value is Nan (abbreviated as "not a number (not a number)"). It is used for all floating point calculations without a good number definition, such as 0.0/0.0. The Specification describes, Nan is not equal to any floating point value, including itself [C # Language Specification 7.9.2]. Therefore, if I is initialized as Nan before the cycle starts, terminate the conditional test (I! = I) The calculation result is true, and the loop will never end. It's strange, but it's a fact.
You can use any floating point arithmetic expression that calculates Nan to initialize I. For example:
Double I = 0.0/0.0;
Similarly, to be clear, you can use the constants provided by the standard class Library:
Double I = double. Nan;
Nan has other amazing features.For any floating point operation, as long as one or more of them is Nan, the result is Nan. [C # Language Specification 4.1.6]. This rule is very reasonable, but it has strange results. For example Program False will be printed:
Class puzzlers29
{
Static void main ()
{
Double I = 0.0/0.0;
System. Console. writeline (I-I = 0 );
}
}
The rule for calculating Nan is based on the following principle: Once a computation generates Nan, it is damaged, and no further computation can fix such damage. The Nan value intentionally causes the damaged computation to continue until it reaches the point where it is convenient to handle this situation.
In short, float and double types both have a special Nan value, which is used to indicate the number of numbers. For calculations involving Nan values, the rules are simple and wise, but the results of these Rules may be intuitive.
C # directory