从44.556677想到的

如下代码:

float a = 44.556677f;
printf("%f\n", a);

得到的输出是什么?并不是44.556677,而是44.556679。浮点数这么坑吗?为什么不一样呢?

浮点数的二进制表示,一种是手算,另一种是直接格式转换然后输出。

手算的,我看的这里的 https://blog.csdn.net/youmeichifan/article/details/80775360

发现44.556677算出来是42323a09,44.556679是42323a0a,两个不一样。计算过程如下:

强转格式输出的,我看的这里的:http://www.cnblogs.com/tlz888/p/9211600.html

44.556677和44.556679的输出都是42323a0a

对应的代码:

//show_float.c 
#include <stdio.h>

unsigned int float2hexRepr(float* a){
    unsigned int c;
    c = ((unsigned int*)a)[0];
    return c;
}

int main(){
    float a = 44.556677f;
    printf("print out 44.556677 but get: %f\n", a);

    printf("44.556677's hex: %x\n", float2hexRepr(&a));

    float b = 44.556679f;
    printf("44.556679's hex: %x\n", float2hexRepr(&b));
   
    return 0;
}

编译运行结果:

print out 44.556677 but get: 44.556679
44.556677's hex: 42323a0a
44.556679's hex: 42323a0a

猜你喜欢

转载自www.cnblogs.com/zjutzz/p/10140559.html