[英]Why two consecutive casting change an integer number?
I wrote the below program : 我写了下面的程序:
#include <iostream>
int main()
{
int i =123456789;
float f=i;
int j=f;
std::cout<<"j-i ="<<j-i;
}
As far as we know, float numbers has at least 4 byte length in the memory. 据我们所知,浮点数在内存中至少有4个字节的长度。 and 123456789
in decimal is equal with 0x75BCD15
in hexadecimal and this is less than 4 byte. 十进制的123456789
等于十六进制的0x75BCD15
,且小于4个字节。 So I why when I run the above program, the output is not 0
? 那么我为什么在运行上述程序时输出不是0
?
ap1019@sharifvm:~$ ./a.out
j-i = 3
Because float
only has 23 bits of precision (*). 因为float
仅具有23位精度(*)。 The other 9 bits are needed for the sign and the exponent. 符号和指数还需要其他9位。 This means that after 16,777,216 you get holes in the "whole numbers" float range. 这意味着在16,777,216之后,您会在“整数”浮动范围内得到漏洞。
(*) Actually 24 bits, but only 23 bits need to be stored; (*)实际上是24位,但是只需要存储23位; the first bit is implied by the exponent. 指数表示第一位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.