问题
Could anyone please me why the output of the following programme is not " different different"?
public static void main(String[] args)
{
float f1=3.2f;
float f2=6.5f;
if(f1==3.2)
System.out.println("same");
else
System.out.println("different");
if(f2==6.5)
System.out.println("same");
else
System.out.println("different");
}
o/p :different same
回答1:
6.5 has a finite binary representation: 110.1
Any floating type with at least 4 significant bits can represent this number perfectly.
110.100000000000000000000 (float)
= 6.5
110.10000000000000000000000000000000000000000000000000 (double)
= 6.5
3.2 on the other hand has an infinite binary representation: 101.0011001100110011...
float and double don't have infinite precision and thus can only approximate this number :(
101.001100110011001100110 (float)
= 3.2000000476837158203125
101.00110011001100110011001100110011001100110011001101 (double)
= 3.20000000000000017763568394002504646778106689453125
As you can clearly see, these numbers are not the same!
回答2:
Because 3.2 is not representable exactly as floating point number and 6.5 is (hint: 6.5 = 13 * 2^(-1)), as well as the fact that 3.2 is a double
literal but 3.2f is a float
literal.
回答3:
Because 3.2f is a float
value and 3.2
is a double
value. Floating point numbers are always slightly inaccurate because binary representation cannot implement them accurately, so comparing them for exact equality is a bad idea. Particularly comparing floats with doubles. Expressions such as 3.2f == 3.2f
are usually okay, but even those can fail in some languages, e.g. if they represent numbers in registers more accurately than in memory.
回答4:
This can help understand
回答5:
"3.2f" is a of type float. "3.2" is of type double.
回答6:
Also, I think anything with a decimal defaults into a double, so when you do a comparison, you have to add 'f' as well like if(f2==6.4f)
.
来源:https://stackoverflow.com/questions/2936219/float-numbers-in-java