为什么我的浮点值不能正确打印? [英] Why Isn't My Floating Point Values Printing Properly?

查看:176
本文介绍了为什么我的浮点值不能正确打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印浮点值0x40a00000和0xc0200000.但是根据IEEE-754浮点转换器( https://www.h-schmidt.net/FloatConverter/IEEE754.html )完全不同:

I am trying to print out the floating point values 0x40a00000 and 0xc0200000. But the values that I print out and the correct values according to the IEEE-754 Floating Point Converter (https://www.h-schmidt.net/FloatConverter/IEEE754.html) are completely different:

我应该根据IEEE转换器获得的值:

The values I should get according to the IEEE converter:

0x3F800000 = 5.00
0xBF000000 = -2.50

我在运行时得到的值:

float tmp1 = 0x40a00000;
float tmp2 = 0xc0200000;

printf("tmp1 = %.2f\n", tmp1);
printf("tmp2 = %.2f\n", tmp2);

tmp1 = 1084227584.00
tmp2 = 3223322624.00

由于某种原因,我的C代码没有按照IEEE标准格式化浮点值的位,而是格式化它们,就好像它是带小数点的整数一样

For some reason my C code isn't formatting the bits of the floating point values according to IEEE standards and is instead formatting them as if it were an int with a decimal point

推荐答案

这些正在将十六进制数字的float表示形式分配给float.

These are assigning the float representation of the hexadecimal numbers to the floats.

相反,请执行以下操作:

Instead, do this:

int i1 = 0x40a00000;
int i2 = 0xc0200000;
float tmp1, tmp2;
memcpy(&tmp1, &i1, sizeof(int));
memcpy(&tmp2, &i2, sizeof(int));

打印它们:

printf("tmp1 = %.2f\n", tmp1);
printf("tmp2 = %.2f\n", tmp2);

输出:

tmp1 = 5.00
tmp2 = -2.50

tmp1 = 5.00
tmp2 = -2.50

完整示例:

#include <stdio.h>
#include <string.h>

int main(void)
{
    int i1 = 0x40a00000;
    int i2 = 0xc0200000;
    float tmp1, tmp2;
    memcpy(&tmp1, &i1, sizeof(int));
    memcpy(&tmp2, &i2, sizeof(int));
    printf("tmp1 = %.2f\n", tmp1);
    printf("tmp2 = %.2f\n", tmp2);
}

这篇关于为什么我的浮点值不能正确打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆