我将正值放入类型为 double 的变量中。
当我看到内存的内容时,符号位是 1。
我认为它应该是0,但它可能是错误的。
为什么符号位是1?
#include<stdio.h>
int main(){
int num=116;
union {float x; int i;} u4;
union {double x; long long int i;} u8;
u4.x = (float) num/10000.0;
u8.x = (double) num/10000.0;
printf("%lx\n",u4.i);
printf("%lx\n",u8.i);
printf("%.30f\n",u4.x);
printf("%.30f\n",u8.x);
return 0;
}
输出:
3c3e0ded
a5119ce0
0.011599999852478504000000000000
0.011599999999999999000000000000
a5119ce0 是 double 类型的输出。
a5119ce0 表示
1010 0101 0001 0001 1001 1100 1110 0000
并且它的符号位是 1,这意味着这是一个负数。
3c3e0ded 是浮点型的输出。
3c3e0ded 表示
0011 1100 0011 1110 0000 1101 1110 1101
对于使用 float 和 double 获得相同长度的结果,我也感到困惑。
如果你编译时出现警告,你的编译器可能会指出你的错误。例如,使用 gcc
:
$ gcc -Wall main.c
main.c: In function ‘main’:
main.c:12:12: warning: format ‘%lx’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘int’ [-Wformat=]
printf("%lx\n",u4.i);
^
main.c:12:12: warning: format ‘%lx’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘int’ [-Wformat=]
main.c:13:12: warning: format ‘%lx’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘long long int’ [-Wformat=]
printf("%lx\n",u8.i);
^
main.c:13:12: warning: format ‘%lx’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘long long int’ [-Wformat=]
进行指示的更正:
printf("%x\n",u4.i);
printf("%llx\n",u8.i);
编译时没有警告并产生预期的输出:
3c3e0ded
3f87c1bda5119ce0
0.011599999852478504180908203125
0.011599999999999999200639422270