printf 不打印正确的浮点值

printf does not print correct float value

我有一个 4 字节的十六进制数,当我将它转换为浮点数时它是 -0.5(我检查了参考资料并且它是正确的),但是 printf 给出了非常错误的值:

 int f=0xBF000000;
 printf("%f",(float)f);  // prints -1090519040.000000

我不知道这里出了什么问题!所有计算器给出的正确值为 -0.5,但 printf 给出的值高于此值。

您的 int 值为 -1090519040。如果你打印它,你会得到这个值:

printf("%d", f); // -1090519040

如果将其类型转换为浮点型,它将采用该值并更改类型但不会值。所以它会导致 -1090519040.0000.

如果您真的想将 int 解释为 float,可以使用指针:

float* p = &f;
printf("%f",*p); // -0.500000

这里有一个指向整数地址的浮点指针,如果打印它,它会将这些位解释为浮点数。

Eric Postpischil 的评论:

float *p = &f; is not a proper way to reinterpret the bytes of an object in C, as it violates the aliasing rule (C 2011 [N1570] 6.5 7, an object’s value shall be accessed only through its effective type, a character type, or certain others).

另一种(更好的)方法是使用 memcopy 并将您的 int 复制到另一个 float 中:

int a = 0xBF000000;
float b = 0;
memcpy(&b, &a, 4);
printf("%f", b); // -0.500000

如果您喜欢访问浮点值的每个字节,您可以使用联合。

typedef union
{
    struct
    {
        uint8_t Byte1;
        uint8_t Byte2;
        uint8_t Byte3;
        uint8_t Byte4;
     };
     float_t FloatValue;
} myFloatT;