用printf打印出的浮动值 [英] using printf to print out floating values
问题描述
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int x, *ptr_x;
float f , *ptr_f;
ptr_f = &f;
ptr_x = &x;
*ptr_x = 5;
*ptr_f = 1.5; //printf("%d %f\n", f,x);
printf ("\n\nxd = %d \t xf = %f \n ff = %f \t fd = %d", x,x,f,f);
return 0;
}
预计不会对FF =%f显示输出。
The output for ff = %f is not expected.
XD = 5 XF = 0.000000
结果 FF = 0.000000 的FD = 1073217536
xd = 5 xf = 0.000000
ff = 0.000000 fd = 1073217536
这在code的一点是要显示,如果一个浮动值印有%D和如果一个int值印制%F会发生什么。
The point of the this code is to show what would happen if a floating value is printed with %d and if a int value is printed %f.
为什么不被打印的浮点值正常,即使我用%F?
Why is the float value not being printed properly even if i use %f ?
推荐答案
的printf()不是类型安全的。
传递给的printf()的参数
根据是什么您的承诺编译器进行处理。
The arguments that you pass to printf()
are treated according to what you promise the compiler.
此外,浮动
,则晋升为双击
当通过可变参数去世了。
Also, float
s are promoted to double
s when passed through variadic arguments.
所以,当你答应编译器%F
第一时间( XF
),编译器消耗了一个整个双击
(通常为8个字节)从参数,吞咽你漂浮在过程中。然后第二个%F
削减对入零尾数的第二个双。
So when you promise the compiler %f
the first time (for xf
), the compiler gobbles up an entire double
(usually 8 byte) from the arguments, swallowing your float in the process. Then the second %f
cuts right into the zero mantissa of the second double.
下面是你的论点图片:
+-0-1-2-3-+-0-1-2-3-+-0-1-2-3-4-5-6-7-+-0-1-2-3-4-5-6-7-+
| x | x | f | f |
+---------+---------+-----------------+-----------------+
%d--------|%f----------------|%f---------------|%d------|
但˚F
看起来像这样(已晋升为双击
)
But f
looks like this (having been promoted to double
):
f = 3FF8000000000000
让我们从价值观再次战平它,猜测你的机器字节顺序:
Let's draw it again with values, and speculating about your machine endianness:
| 05000000 | 05000000 | 00000000 0000F83F | 00000000 0000F83F |
| %d, OK | %f, denormal... | %f, denormal... | %d, OK |
注意,1073217536是0x3FF80000。
Note that 1073217536 is 0x3FF80000.
这篇关于用printf打印出的浮动值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!