c - c中的浮点不准确

标签 c floating-point

我知道浮点值在可以准确表达的数字中是有限的,我发现很多网站都描述了为什么会发生这种情况。但我还没有找到任何关于如何有效处理这个问题的信息。但我敢肯定 NASA 不同意 0.2/0.1 = 0.199999。示例:

#include <stdio.h>
#include <float.h> 
#include <math.h>

int main(void)
{
    float number = 4.20;
    float denominator = 0.25;

    printf("number = %f\n", number);
    printf("denominator = %f\n", denominator);
    printf("quotient as a float = %f should be 16.8\n", number/denominator);
    printf("the remainder of 4.20 / 0.25 = %f\n", number - ((int) number/denominator)*denominator);
    printf("now if i divide 0.20000 by 0.1 i get %f not 2\n", ( number - ((int) number/denominator)*denominator)/0.1);
}

输出:

number = 4.200000
denominator = 0.250000
quotient as a float = 16.799999 should be 16.8
the remainder of 4.20 / 0.25 = 0.200000
now if i divide 0.20000 by 0.1 i get 1.999998 not 2

那么我如何使用 float (或小数或 double )进行算术运算并获得准确的结果。希望我没有错过一些非常明显的事情。任何帮助都是极好的!谢谢。

最佳答案

解决方案是在不能接受舍入误差的应用程序中不使用 float 。使用扩展精度库(又名任意精度库),如 GNU MP Bignum .参见 this Wikipedia page一个不错的任意精度库列表。另请参阅关于 rational data types 的维基百科文章和 this thread了解更多信息。

如果您打算使用浮点表示法(floatdouble 等),那么使用可接受的方法编写代码来处理舍入错误(例如,避免 ==)。有很多关于如何执行此操作的在线文献,并且方法因所涉及的应用程序和算法而异。

关于c - c中的浮点不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40168077/

相关文章:

c - 浮点精度与实际分配的值不匹配?

c++ - 当服务器将数据作为 c 结构发送时,我们可以在客户端将缓冲区类型转换为 C++ 结构吗?

c - 计算平均值的奇怪问题

c - c中这些数组的值(value)是什么?

c - 为什么我无法从列表中删除节点?

c - float 不添加?

c - 如何将 char 指针中存储的两个数字相加?

math - float 学有问题吗?

java - roundToDecimals 返回太多数字

c# - 为什么这个循环只有在我不调试的时候才会无限循环?