面试问题打印一个浮点数 [英] interview question printing a floating point number
问题描述
什么是以下程序的输出,为什么?
What's the output of the following program and why?
#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
return 0;
}
我的编译器打印0和1095237632.为什么?
My compiler prints 0 and 1095237632. Why?
推荐答案
在这两种情况下你传递一个比特重新presenting浮点值,并将其打印为十进制。第二种情况是简单的情况下,这里的输出是相同的浮点数的底层再presentation。 (这是假设调用约定指定一个浮动
的值传递相同的方法, INT
是,这不能保证。)
In both cases you pass a bits representing floating-point values, and print them as decimal. The second case is the simple case, here the output is the same as the underlying representation of the floating-point number. (This assumes that the calling convention specified that the value of a float
is passed the same way an int
is, which is not guaranteed.)
然而,在第一种情况下,当你路过一个浮动
像的printf
A可变参数的功能是促进到双击
。这意味着,传递的值将是64位,而的printf
将拿起它(或者垃圾)或者一半。在你的情况下,它显然已经拿起了32个最显著位,因为它们通常会在浮动
到双击$ C $毕竟零C>演员。
However, in the first case, when you pass a float
to a vararg function like printf
it is promoted to a double
. This mean that the value passed will be 64 bits, and printf
will pick up either half of it (or perhaps garbage). In your case it has apparently picked up the 32 least significant bits, as they typically will be all zero after a float
to double
cast.
只是为了绝对清楚,在这个问题的code是的不的有效C,因为它是非法的值传递给的printf
不匹配的格式说明。
Just to make it absolutely clear, the code in the question is not valid C, as it's illegal to pass values to printf
that does not match the format specifier.
这篇关于面试问题打印一个浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!