如何在C ++中生成精确的舍入值?

时间:2018-05-12 18:14:33

标签: c++ rounding

我一直在研究用C ++中指定的小数位来舍入双打。我找到了一种方法来实现这一目标,但它似乎有点偏离。在舍入值结束时有一个小的不精确性。

这是我展示问题的示例程序......在此示例中,值0.929383191应舍入为0.929(或至少0.92900000000000000)。但是,我得到的值为0.92900000000000005。这是一个相当微不足道的差异,但我希望它是准确的。这可能吗?

#include "stdafx.h"
#include <math.h>

// round float to n decimals precision
const double RoundToNearestDecimalPlace(
   double value, 
   int decimal_place)
{
   if (value == 0.0)
      return 0.0;

   double factor = pow(10.0, decimal_place - ceil(log10(fabs(value))));
   return round(value * factor) / factor;
}

int main()
{
   const double Result = RoundToNearestDecimalPlace(0.929383191, 3);

   return 0;
}

0 个答案:

没有答案
相关问题