好吧——我几乎不好意思在这里张贴这个(如果有人投票关闭,我会删除),因为这似乎是一个基本的问题。

这是在c++中四舍五入到一个数字的倍数的正确方法吗?

我知道还有其他与此相关的问题,但我特别感兴趣的是,在c++中做这件事的最佳方法是什么:

int roundUp(int numToRound, int multiple)
{
 if(multiple == 0)
 {
  return numToRound;
 }

 int roundDown = ( (int) (numToRound) / multiple) * multiple;
 int roundUp = roundDown + multiple; 
 int roundCalc = roundUp;
 return (roundCalc);
}

更新: 抱歉,我可能没把意思说清楚。下面是一些例子:

roundUp(7, 100)
//return 100

roundUp(117, 100)
//return 200

roundUp(477, 100)
//return 500

roundUp(1077, 100)
//return 1100

roundUp(52, 20)
//return 60

roundUp(74, 30)
//return 90

当前回答

如果x已经是一个倍数,我使用模的组合来取消余数的加法:

int round_up(int x, int div)
{
    return x + (div - x % div) % div;
}

我们求余数的倒数然后再用除数求模如果它是除数本身,再加上x。

round_up(19, 3) = 21

其他回答

这里有一个超级简单的解决方案来展示优雅的概念。它主要用于网格快照。

(伪代码)

nearestPos = Math.Ceil( numberToRound / multiple ) * multiple;

以下是我根据OP的建议和其他人给出的例子给出的解决方案。因为大多数人都在寻找它来处理负数,这个解决方案就是这样做的,而不使用任何特殊的功能,如腹肌等。

通过避免使用模数而使用除法,负数是一个自然的结果,尽管它是四舍五入。在计算出向下舍入的版本之后,它会执行所需的数学运算以向上舍入,或者向负方向舍入,或者向正方向舍入。

还要注意的是,没有使用特殊的函数来计算任何东西,所以这里有一个小的速度提升。

int RoundUp(int n, int multiple)
{
    // prevent divide by 0 by returning n
    if (multiple == 0) return n;

    // calculate the rounded down version
    int roundedDown = n / multiple * multiple;

    // if the rounded version and original are the same, then return the original
    if (roundedDown == n) return n;

    // handle negative number and round up according to the sign
    // NOTE: if n is < 0 then subtract the multiple, otherwise add it
    return (n < 0) ? roundedDown - multiple : roundedDown + multiple;
}

可能更安全的方法是强制转换为浮点数并使用ceil()—除非您知道int除法将产生正确的结果。

这是对“如何求出n位需要多少字节?”(A:(n位+ 7)/ 8)。

int RoundUp(int n, int roundTo)
{
    // fails on negative?  What does that mean?
    if (roundTo == 0) return 0;
    return ((n + roundTo - 1) / roundTo) * roundTo; // edit - fixed error
}
int roundUp(int numToRound, int multiple)
{
 if(multiple == 0)
 {
  return 0;
 }
 return ((numToRound - 1) / multiple + 1) * multiple;  
}

没有必要在条件上添乱