奇怪的printf输出 [英] Strange printf output
问题描述
我执行以下code
#include <stdio.h>
int main()
{
printf("%f\n", 9/5);
}
输出: 0.000000
为什么不 1
?
如果我写的printf(%F%F%D \\ n,(浮点)9/5,4的sizeof(浮动)的sizeof(INT));
然后输出 1.800000 0.000000 4 59
为什么不 1.800000 4 4 4
在我的机器上的的sizeof(浮动)
是 4
在此先感谢
推荐答案
这是因为你的的printf
格式说明符不符合你通过它:
This is because your printf
format specifier doesn't match what you passed it:
9/5
的类型为 INT
。但的printf
需要一个浮动
。
9/5
is of type int
. But printf
expects a float
.
所以,你需要或者将它转换为float或作出任何面值的浮动:
So you need to either cast it to a float or make either literal a float:
printf("%f\n", (float)9/5);
printf("%f\n", 9./5);
至于为什么你得到 0.0
,这是因为的printf()
正在读二重$ 1
的对$ psentation(整数)并打印其作为浮动
。这恰好是一个小非标准化的值,这是非常接近 0.0
。
As for why you're getting 0.0
, it's because the printf()
is reading the binary representation of 1
(an integer) and printing it as a float
. Which happens to be a small denormalized value that is very close to 0.0
.
编辑:还有一些与可变参数的类型推广会
EDIT : There's also something going with type-promotion on varargs.
在可变参数的功能,浮动
提升为双击
。因此,的printf()
在这种情况下,实际上需要一个64位的参数拿着双击
。但是,你只能通过它的32位操作数,所以它实际上是从堆栈(这恰好是零在这种情况下)读取一个额外的32位 - 更不确定的行为
In vararg functions, float
is promoted to double
. So printf()
in this case actually expects a 64-bit parameter holding a double
. But you only passed it a 32-bit operand so it's actually reading an extra 32-bits from the stack (which happens to be zero in this case) - even more undefined behavior.
这篇关于奇怪的printf输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!