c中的浮点不准确

5 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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

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

Ted*_*opp 5

解决方案是在无法接受舍入误差的应用程序中不要使用浮点数。使用扩展精度库(又名任意精度库),例如GNU MP Bignum。有关任意精度库的详细列表,请参阅此维基百科页面。另请参阅有关理性数据类型的维基百科文章和此线程以获取更多信息。

如果您打算使用浮点表示(floatdouble等),则使用可接受的方法编写代码来处理舍入错误(例如,避免==)。有很多关于如何做到这一点的在线文献,并且根据所涉及的应用程序和算法,方法也有很大差异。