c - 为什么即使我们将正分数放入 double 类型,符号位仍为 1 的原因

标签 c

<分区>

我将正值放入类型为 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

关于c - 为什么即使我们将正分数放入 double 类型,符号位仍为 1 的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55672469/

相关文章:

c - 来自内核崩溃的 Linux 系统调用(奇怪的偏移量)

c - 尝试创建排序程序,但未按预期工作

c - 有没有一种特殊的方法可以从 c 中的文件中删除记录而不创建它的副本?

c - "%FF"目录错误?似乎是由于触摸 [C]

c - 在头文件中解析 “error: expected identifier”?

c - "Replay"tcpdump 文件

c - 我如何正确地在 C 中进行键捕获?

c - pthread(段错误)

c - 这个函数中的 `if(!found)`是如何工作的?

CS50 - 恢复 - 操作 Card.raw PSET3