将 double 转换为 10 的 int 倍数

Transform double to int multiple of 10

我有一个从公式计算的双精度列表。例如,其中一个 double 是 88.32547。我想将它们转换成最接近的10的整数倍,并把它们放在另一个变量中。

在示例中,double a = 88.32547 导致 int b = 90,或者如果 double a = -65.32547 导致 int b = -70

最简单的方法就是这样

int a = (round(x / 10.0) * 10)

除以十(将小数点向左移动),四舍五入(得到最接近的整数)然后再乘以十。

10*std::round(x/10)

您可能想要添加一个 int 转换:

int(10*std::round(x/10))

详情见http://en.cppreference.com/w/cpp/numeric/math/round

将数字除以 10,舍入到最接近的整数,然后再乘以 10。

示例:

  • 10 × round(88.32547 / 10) = 10 × round(8.832547) = 10 × 9 = 90
  • 10 × round(−65.32547 / 10) = 10 × round(−6.532547) = 10 × −7 = −70

四舍五入可以考虑使用std::round.

在我无法使用 Round 的情况下,我使用了类似的东西(我需要一些特定的负整数):

bottomValue = floor(a/10)*10;
topValue    = ceil(a/10)*10;
if(a-bottomValue < topValue-a)
    return bottomValue;
else
    return topValue;

如果你可以使用圆形:

roundValue = round(a/10)*10;
return roundValue;