Reprinted please indicate, http://www.gxabase.com
The following program has a single-weight loop, which records the number of iterations and prints the number at the end of the loop. So what will this program print?
START = 2000000000 count = 0 ( f = START; f < START + 50; f++ count++ }
The surface analysis may assume that this program will print 50. After all, the loop variable (f) is initialized to 2000000000, and the end value is 50 larger than the initial value, and this loop has the traditional "half open" form: it uses the <operator, which includes the initial value but does not include the termination value.
However, this analysis misses the key point: the cyclic variable is of the float type, rather than the int type. The initial value of f is close to Integer. MAX_VALUE. Therefore, it must be expressed accurately with 31 bits, while the float type can only provide 24 bits. Incremental operations on such a huge float value will not change its value. Therefore, this program seems to be infinite, because f will never solve its termination value. However, if you run the program, you will find that it does not have an infinite loop. In fact, it immediately terminates and prints 0. What's going on?
The problem is that the conditional test fails, and the method is similar to that of the incremental operation failure. This loop runs only when the round-robin index f is smaller than (float) (START + 50. When comparing an int with a float, the upgrade from int to float is automatically performed. Unfortunately, this improvement will lead to the loss of precision among the three types of original type conversion. (The other two are from long to float and from long to double .)
The initial value of f is too large, so that when 50 is added to it and the result is converted to float, the resulting value is equivalent to directly converting f to the float value. In other words, (float) 2000000000 = 2000000050, so the expression f <START + 50 is false even before the first execution of the loop body, so the loop body will never run.
It is very easy to correct this program. You only need to change the type of the loop variable from float to int. This avoids all inaccuracy related to floating point calculation:
( f = START; f < START + 50; f++ count++;
The implication of this puzzle is simple: Do not use floating-point numbers as cyclic indexes because they can lead to unpredictable behavior. If you need a floating point number in a loop, use an int or long loop index and convert it to float or double. When converting an int or long into a float or double, you may lose precision, but at least it will not affect the Loop itself. When you use floating point numbers, you must use double instead of float, unless you are sure that float provides sufficient precision and there are mandatory performance requirements that force you to use float. It is very rare to use float instead of double.