将双精度转换为 10 的整数倍

Transform double to int multiple of 10

本文关键字:整数 双精度 转换      更新时间:2023-10-16

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

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

10*std::round(x/10)

你可能想添加一个 int cast:

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

有关详细信息,请参阅 http://en.cppreference.com/w/cpp/numeric/math/round

最简单的方法是这样的

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

除以十(

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

在我无法使用 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;

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

例子:

  • 10 × 轮(88.32547/10( = 10 × 轮(8.832547( = 10 × 9 = 90
  • 10 × 舍入(−65.32547/10( = 10 × 舍入(−6.532547( = 10 × −7 = −70

对于四舍五入,您可以考虑使用 std::round