能否请您解释以下代码的结果:
float f = 1.56898138E+09f;
double d = 1.56898138E+09;
int i = 1568981320;
bool a = f > i; //false
bool b = d > i; //true
bool c = (int)f > i; //true
为什么是a == false
?
答案 0 :(得分:4)
从int到float有隐式转换。这是有损隐式转换的罕见示例。
(float)1568981320 = 1568981376f
,该值与f
相同,因此不能大于或小于该值。
答案 1 :(得分:2)
好吧,int
使用 all 32
位存储整数值
1568981320 == 1011101100001001100000101001000 (binary)
当float
仅将23
位https://en.wikipedia.org/wiki/Single-precision_floating-point_format与{em> 一起使用时,因此
最初的1
应该四舍五入:
1011101100001001100000101001000
因此,在舍入时,我们应该丢掉 1011101100001001100000101001000
^
^ from this on we should throw the "1001000" bits away
|
this 1 can be skipped since float assumes that the 1st bit is always 1
并添加1001000
:
1
这是 1011101100001001100000101001000 - original value (1568981320)
1011101100001001100000110000000 - rounded value (1568981376)
^ ^
will be stored in float
的值,比原始1568981376