0

我有这个简单的程序

#include <stdio.h>
int main(void)
{
 unsigned int a = 0x120;
 float b = 1.2;
 printf("%X %X\n", b, a);
 return 0;
}

我希望输出是

some-value 120  (some-value will depend on the bit pattern of `float b` )

但我看到

40000000 3FF33333

为什么被a搞砸的价值?%X将它的参数视为signed int,因此它应该从堆栈中检索 4 个字节并打印 calue,b然后获取接下来的 4 个字节打印其a值为0x120

4

2 回答 2

8

首先,将参数传递给printf不匹配格式说明符是未定义的行为。

其次,传递给 时float会提升为,所以它是八个字节而不是四个。哪些字节被解释为格式所期望的两个值取决于推送参数的顺序。doubleprintfunsignedprintf

于 2012-05-03T18:05:23.120 回答
2

如果您想查看存储的浮点数的位,请使用联合:

 float b = 1.2;
 union {
      float  f;
      int    i;
 } u;
 u.f = b;

 printf ("%x\n", u.i);

结果(32 位 x86):

3f99999a
于 2012-05-03T18:11:30.367 回答