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

这是在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

当前回答

这就是我要做的:

#include <cmath>

int roundUp(int numToRound, int multiple)
{
    // if our number is zero, return immediately
   if (numToRound == 0)
        return multiple;

    // if multiplier is zero, return immediately
    if (multiple == 0)
        return numToRound;

    // how many times are number greater than multiple
    float rounds = static_cast<float>(numToRound) / static_cast<float>(multiple);

    // determine, whether if number is multiplier of multiple
    int floorRounds = static_cast<int>(floor(rounds));

    if (rounds - floorRounds > 0)
        // multiple is not multiplier of number -> advance to the next multiplier
        return (floorRounds+1) * multiple;
    else
        // multiple is multiplier of number -> return actual multiplier
        return (floorRounds) * multiple;
}

代码可能不是最优的,但比起枯燥的性能,我更喜欢干净的代码。

其他回答

没有条件:

int roundUp(int numToRound, int multiple) 
{
    assert(multiple);
    return ((numToRound + multiple - 1) / multiple) * multiple;
}

这就像对负数进行舍入一样


同样适用于负数的版本:

int roundUp(int numToRound, int multiple) 
{
    assert(multiple);
    int isPositive = (int)(numToRound >= 0);
    return ((numToRound + isPositive * (multiple - 1)) / multiple) * multiple;
}

测试


如果倍数是2的幂(快3.7倍)

int roundUp(int numToRound, int multiple) 
{
    assert(multiple && ((multiple & (multiple - 1)) == 0));
    return (numToRound + multiple - 1) & -multiple;
}

测试

对于负numToRound:

这应该很容易做到,但标准的模%运算符并不像人们期望的那样处理负数。例如- 14% 12 = -2而不是10。首先要做的是得到一个永不返回负数的模运算符。roundUp非常简单。

public static int mod(int x, int n) 
{
    return ((x % n) + n) % n;
}

public static int roundUp(int numToRound, int multiple) 
{
    return numRound + mod(-numToRound, multiple);
}

我发现了一个算法,有点类似于上面发布的:

Int [(|x|+n-1)/n]*[(nx)/|x|],其中x是用户输入的值,n是使用的倍数。

它适用于所有值x,其中x是整数(正或负,包括零)。我专门为c++程序编写了它,但基本上可以在任何语言中实现。

首先,因为我不太明白你想要做什么,这些台词

int roundUp = roundDown + multiple;
int roundCalc = roundUp;
return (roundCalc); 

肯定可以缩写为

int roundUp = roundDown + multiple;
return roundUp;

当factor总是为正时,这种方法有效:

int round_up(int num, int factor)
{
    return num + factor - 1 - (num + factor - 1) % factor;
}

编辑:返回round_up(0,100)=100。请参阅下面Paul的评论,了解返回round_up(0,100)=0的解决方案。