c - ARM 上的 C 中的浮点转换

标签 c floating-point

我尝试将两个字节转换为 float ,但精度有问题。 就我而言,我读取 temp 并存储到两个字节中。例如,14.69*C - 14(dec) 为一个字节,69(dec) 为第二个字节。然后我想将此字节转换为 float 并与另一个 float 进行比较,例如:

byte byte1 = 0xE;
byte byte2 = 0x45;

float temp1 = (float) byte1*1.0 + (float) byte2*0.01; // byte2*0.1 if byte2<10
float temp2 = 14.69;
...
if (temp1==temp2){
  ...
}

我期望 temp1 值 14.69,但值是 14.68999958 - 为什么,解决方案是什么?

最佳答案

每次进行浮点运算时,都会丢失一些精度。您可以尝试通过尽可能用 int 代替浮点运算来减少错误。例如:

((float)((unsigned int)byte1 * 100 + (unsigned int)byte2))/100.0

此外,由于机器精度问题,比较 float 是否严格相等可能会失败,您应该使用 if (fabsf(f1 - f2) < EPSILON)

关于c - ARM 上的 C 中的浮点转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681353/

相关文章:

C 输出格式问题

c - 如何确保用户输入的数据是整数

c - 在本地安全地存储密码

python - 值错误 : could not convert string to float: '" "'

architecture - 32位 float 可以表示多少个数字

c - 为什么编译时需要包含.o文件?

java - 自动为枚举添加类似 Java 枚举的功能

algorithm - 你如何计算除 10 以外的基数中的 float ?

javascript - 2的补码和IEEE754有什么关系?

c - floor(a/(double)b​​)*b==a 如果 a%b==0 在 C 中?