First, let's look at the two programs on geeksforgeeks:
Procedure 1:
# Include <stdio. h> int main () {float x = 0.1; If (x = 0.1) printf ("if"); else if (x = 0.1f) printf ("else if"); else printf ("else ");}
Procedure 2:
# Include <stdio. h> int main () {float x = 0.5; If (x = 0.5) printf ("if"); else if (x = 0.5f) printf ("else if"); else printf ("else"); System ("pause"); Return 0 ;}
The output of program 1 is else if, while that of Program 2 is: if
Why?
This is because the precision of double and float is different. If the decimal point is converted to binary without an infinite loop, the comparison value is different, such as 0.1. Otherwise, float and double can be compared, the result value is equal, for example, 0.5.
In this case, we need to apply the knowledge of converting decimals to binary. The so-called multiplication 2 is an integer.
For example, 0.1 is converted to binary:
0.1*2 = 0.2 ---- the integer is 0, so this bit is 0.
0.2*2 = 0.4 ----- the integer is 0. Continue with 0.
0.4*2 = 0.8 ----- the integer is zero and the value is zero.
0.8*2 = 1.6 ----- the integer is 1, and the value is 1.
0.6*2 = 1.2 ---- 1
0.2*2 = 0.4 --- take zero, and the previous loop.
So 0.1 (base 10) = 0.00011 0011 0011... (0011 is an infinite loop digital value)
If such a number has different precision, it will definitely lead to different values.
So :( float) 0.1! = Double (0, 0.1)
But 0.5 (base 10) = 0.1 (base 2), no infinite cyclic digits
So :( float) 0.5 = double (0.5)
Reference: http://www.geeksforgeeks.org/comparison-float-value-c/