首页 > 解决方案 > 输入double变小了,没有明显的原因

问题描述

因此,当我输入像 12.45 这样的十进制数时,它会减少 0.00001 或导致我的函数无法正常工作的东西。

例如:如果 x 是 12.45,div 是 0.1,看 x 可以看到变成 12.449999999

但是如果 x 是 12.455 并且 div 是 0.01 它不会减少 x

double round(double x, double div){
if (div != 0){
double temp2 = 0;
int temp = x;
double dec = x - temp;
dec = dec/div;
temp = dec;
temp2 = dec-temp;
temp2 = temp2 * div;
cout << x << endl << endl;
if (temp2 >= div/2){
    x+=(div-temp2);
}else{
    x-=temp2;
}
cout << temp << "  " << dec << "  " << x << "  " << temp2 << "  " << div/2;
return x;
   }else{
    cout << "div cant be equal to zero" << endl;
}
}

我试图制作一个四舍五入的函数。我知道它可能不是最好的做法,但除了我之前描述的问题之外,它可以工作。

为了解决这个问题,我尝试在输入中限制小数位,但没有奏效。还尝试使用其他方法而不是使用双精度/整数组合而没有任何结果。

当 x 为 12.45 且 div 为 0.1 时,我希望输出为 12.5,但它不起作用,因为输入的 0.000001 丢失了。

标签: c++

解决方案


您的程序将被错过通知并且将无法运行。

这就是本标准中定义的编程语言中浮点值的处理方式。
https://en.wikipedia.org/wiki/IEEE_754#Basic_formats

由于操作的结果,它们通常需要四舍五入以适应它们的有限表示,从而使它们难以比较。
https://www.boost.org/doc/libs/1_36_0/libs/test/doc/html/utf/testing-tools/floating_point_comparison.html

您看到的问题是舍入误差的产物。
https://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf


推荐阅读