的printf(QUOT;%F&QUOT ;, AA)时,AA是int类型 [英] printf("%f", aa) when aa is of type int
问题描述
double a = 3.1456;
int aa=2.0;
printf ("%f \n",a );
printf("%f \n",aa);
答案是: 3.145600,3.145599。
我已经尝试了不同的值,并且输出AA似乎有一定的关系。
我很困惑。什么原因?
〜结果
〜结果
〜结果
〜
The answer is 3.145600 ,3.145599.
I have tried different values of a, and the outputs aa seem to have some relationship with a.
I am confused. What's the reason?
~
~
~
~
推荐答案
英戈伦哈德是正确地说,你的程序行为是不确定的 - 输出不会成为下优化或在不同的架构/编译器保持一致。
Ingo Leonhardt is correct to say that your program's behaviour is undefined - the output isn't going to be consistent under optimisation or on different architectures / compilers.
但是,你看到3.1456在这种情况下,突变为3.145599的具体原因是可解释的。由此可以推断,你的架构采用IEEE-754 8个字节的双击
和4个字节的小端 INT
秒。最近的8字节双至3.1456的十六进制再presentation是:
However, the specific reason that you're seeing 3.1456 mutated to 3.145599 in this case is explicable. It can be inferred that your architecture uses IEEE-754 8-byte double
s and 4-byte little-endian int
s. The hexadecimal representation of the nearest 8-byte double to 3.1456 is:
0x40092a305532617c
,其中的符号 0
,指数字段是 0x400的
(重presenting 1指数)和尾数字段是 0x92a305532617c
(重presenting 0x1.92a305532617c十六进制尾数)。如果覆盖的4字节整数2的低4个字节的这一点,那么你会得到:
where the sign is 0
, the exponent field is 0x400
(representing an exponent of 1) and the mantissa field is 0x92a305532617c
(representing a hexadecimal mantissa of 0x1.92a305532617c). If you overwrite the lower 4 bytes of this with the 4-byte integer 2, then you get:
0x40092a3000000002
这具有符号和指数不变,但尾数变为0x1.92a3000000002,或比原始0x0.000005532617a以下。随着1的指数,这个重新presents的0x0.00000aa64c2f4差异,这在小数为〜0.000000634766。当您从3.1456减去这个你〜3.145599365234,这轮以3.145599。
This has the sign and exponent unchanged, but the mantissa has changed to 0x1.92a3000000002, or 0x0.000005532617a less than the original. With an exponent of 1, this represents a difference of 0x0.00000aa64c2f4, which in decimal is ~0.000000634766. When you subtract this from 3.1456 you get ~3.145599365234, which rounds to 3.145599.
这篇关于的printf(QUOT;%F&QUOT ;, AA)时,AA是int类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!