简体   繁体   English

四舍五入到最接近的数字倍数

[英]Rounding up to the nearest multiple of a number

OK - I'm almost embarrassed posting this here (and I will delete if anyone votes to close) as it seems like a basic question.好的 - 我几乎不好意思在这里发帖(如果有人投票关闭,我会删除),因为这似乎是一个基本问题。

Is this the correct way to round up to a multiple of a number in C++?这是在 C++ 中四舍五入到一个数字的倍数的正确方法吗?

I know there are other questions related to this but I am specficially interested to know what is the best way to do this in 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);
}

Update: Sorry I probably didn't make intention clear.更新:抱歉,我可能没有明确表达意图。 Here are some examples:这里有些例子:

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

This works for positive numbers, not sure about negative.这适用于正数,不确定负数。 It only uses integer math.它只使用整数数学。

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

    int remainder = numToRound % multiple;
    if (remainder == 0)
        return numToRound;

    return numToRound + multiple - remainder;
}

Edit: Here's a version that works with negative numbers, if by "up" you mean a result that's always >= the input.编辑:这是一个适用于负数的版本,如果“向上”表示结果总是 >= 输入。

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

    int remainder = abs(numToRound) % multiple;
    if (remainder == 0)
        return numToRound;

    if (numToRound < 0)
        return -(abs(numToRound) - remainder);
    else
        return numToRound + multiple - remainder;
}

Without conditions:无条件:

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

This works like rounding away from zero for negative numbers这就像为负数从零舍入

EDIT: Version that works also for negative numbers编辑:也适用于负数的版本

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

Tests测试


If multiple is a power of 2 (faster in ~3.7 times http://quick-bench.com/sgPEZV9AUDqtx2uujRSa3-eTE80 )如果multiple是 2 的幂(快 3.7 倍http://quick-bench.com/sgPEZV9AUDqtx2uujRSa3-eTE80

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

Tests测试

This works when factor will always be positive:当因子始终为正时,此方法有效:

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

Edit: This returns round_up(0,100)=100 .编辑:这将返回round_up(0,100)=100 Please see Paul's comment below for a solution that returns round_up(0,100)=0 .请参阅下面 Paul 的评论,了解返回round_up(0,100)=0的解决方案。

This is a generalization of the problem of "how do I find out how many bytes n bits will take? (A: (n bits + 7) / 8).这是“我如何找出 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;  
}

And no need to mess around with conditions并且不需要乱七八糟的条件

This is the modern c++ approach using a template function which is working for float, double, long, int and short (but not for long long, and long double because of the used double values).这是使用模板函数的现代 C++ 方法,该函数适用于 float、double、long、int 和 short(但不适用于 long long 和 long double,因为使用了 double 值)。

#include <cmath>
#include <iostream>

template<typename T>
T roundMultiple( T value, T multiple )
{
    if (multiple == 0) return value;
    return static_cast<T>(std::round(static_cast<double>(value)/static_cast<double>(multiple))*static_cast<double>(multiple));
}

int main()
{
    std::cout << roundMultiple(39298.0, 100.0) << std::endl;
    std::cout << roundMultiple(20930.0f, 1000.0f) << std::endl;
    std::cout << roundMultiple(287399, 10) << std::endl;
}

But you can easily add support for long long and long double with template specialisation as shown below:但是您可以使用模板专业化轻松添加对long longlong double支持,如下所示:

template<>
long double roundMultiple<long double>( long double value, long double multiple)
{
    if (multiple == 0.0l) return value;
    return std::round(value/multiple)*multiple;
}

template<>
long long roundMultiple<long long>( long long value, long long multiple)
{
    if (multiple == 0.0l) return value;
    return static_cast<long long>(std::round(static_cast<long double>(value)/static_cast<long double>(multiple))*static_cast<long double>(multiple));
}

To create functions to round up, use std::ceil and to always round down use std::floor .要创建向上舍入的函数,请使用std::ceil并始终向下舍入使用std::floor My example from above is rounding using std::round .我上面的例子是使用std::round舍入。

Create the "round up" or better known as "round ceiling" template function as shown below:创建“向上舍入”或更广为人知的“圆形天花板”模板函数,如下所示:

template<typename T>
T roundCeilMultiple( T value, T multiple )
{
    if (multiple == 0) return value;
    return static_cast<T>(std::ceil(static_cast<double>(value)/static_cast<double>(multiple))*static_cast<double>(multiple));
}

Create the "round down" or better known as "round floor" template function as shown below:创建“round down”或更广为人知的“round floor”模板函数,如下所示:

template<typename T>
T roundFloorMultiple( T value, T multiple )
{
    if (multiple == 0) return value;
    return static_cast<T>(std::floor(static_cast<double>(value)/static_cast<double>(multiple))*static_cast<double>(multiple));
}

For anyone looking for a short and sweet answer.对于任何寻求简短而甜蜜的答案的人。 This is what I used.这是我用的。 No accounting for negatives.不考虑负数。

n - (n % r)

That will return the previous factor.这将返回前一个因素。

(n + r) - (n % r)

Will return the next.下次还会再来。 Hope this helps someone.希望这可以帮助某人。 :) :)

float roundUp(float number, float fixedBase) {
    if (fixedBase != 0 && number != 0) {
        float sign = number > 0 ? 1 : -1;
        number *= sign;
        number /= fixedBase;
        int fixedPoint = (int) ceil(number);
        number = fixedPoint * fixedBase;
        number *= sign;
    }
    return number;
}

This works for any float number or base (eg you can round -4 to the nearest 6.75).这适用于任何浮点数或基数(例如,您可以将 -4 舍入到最接近的 6.75)。 In essence it is converting to fixed point, rounding there, then converting back.本质上它是转换为定点,在那里四舍五入,然后转换回来。 It handles negatives by rounding AWAY from 0. It also handles a negative round to value by essentially turning the function into roundDown.它通过从 0 舍入 AWAY 来处理负数。它还通过基本上将函数转换为 roundDown 来处理负数舍入到值。

An int specific version looks like:特定于 int 的版本如下所示:

int roundUp(int number, int fixedBase) {
    if (fixedBase != 0 && number != 0) {
        int sign = number > 0 ? 1 : -1;
        int baseSign = fixedBase > 0 ? 1 : 0;
        number *= sign;
        int fixedPoint = (number + baseSign * (fixedBase - 1)) / fixedBase;
        number = fixedPoint * fixedBase;
        number *= sign;
    }
    return number;
}

Which is more or less plinth's answer, with the added negative input support.这或多或少是底座的答案,增加了负输入支持。

First off, your error condition (multiple == 0) should probably have a return value.首先,您的错误条件(multiple == 0)可能应该有一个返回值。 What?什么? I don't know.我不知道。 Maybe you want to throw an exception, that's up to you.也许你想抛出一个异常,这取决于你。 But, returning nothing is dangerous.但是,什么都不返回是危险的。

Second, you should check that numToRound isn't already a multiple.其次,您应该检查 numToRound 是否已经不是倍数。 Otherwise, when you add multiple to roundDown , you'll get the wrong answer.否则,当您将multiple添加到roundDown ,您会得到错误的答案。

Thirdly, your casts are wrong.第三,你的演员阵容是错误的。 You cast numToRound to an integer, but it's already an integer.您将numToRound转换为整数,但它已经是整数。 You need to cast to to double before the division, and back to int after the multiplication.您需要在除法之前转换为 double ,并在乘法之后返回 int 。

Lastly, what do you want for negative numbers?最后,你想要什么负数? Rounding "up" can mean rounding to zero (rounding in the same direction as positive numbers), or away from zero (a "larger" negative number). “向上”四舍五入可能意味着四舍五入到零(以与正数相同的方向四舍五入)或远离零(“更大”的负数)。 Or, maybe you don't care.或者,也许你不在乎。

Here's a version with the first three fixes, but I don't deal with the negative issue:这是包含前三个修复程序的版本,但我不处理负面问题:

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

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

Round to Power of Two:轮到二的幂:

Just in case anyone needs a solution for positive numbers rounded to the nearest multiple of a power of two (because that's how I ended up here):以防万一有人需要将正数四舍五入到最接近的 2 的幂的倍数的解决方案(因为这就是我在这里结束的方式):

// number: the number to be rounded (ex: 5, 123, 98345, etc.)
// pow2:   the power to be rounded to (ex: to round to 16, use '4')
int roundPow2 (int number, int pow2) {
    pow2--;                     // because (2 exp x) == (1 << (x -1))
    pow2 = 0x01 << pow2;

    pow2--;                     // because for any
                                //
                                // (x = 2 exp x)
                                //
                                // subtracting one will
                                // yield a field of ones
                                // which we can use in a
                                // bitwise OR

    number--;                   // yield a similar field for
                                // bitwise OR
    number = number | pow2;
    number++;                   // restore value by adding one back

    return number;
}

The input number will stay the same if it is already a multiple.如果它已经是倍数,则输入数字将保持不变。

Here is the x86_64 output that GCC gives with -O2 or -Os (9Sep2013 Build - godbolt GCC online):这是 GCC 使用-O2-Os提供的 x86_64 输出(9Sep2013 Build - Godbolt GCC online):

roundPow2(int, int):
    lea ecx, [rsi-1]
    mov eax, 1
    sub edi, 1
    sal eax, cl
    sub eax, 1
    or  eax, edi
    add eax, 1
    ret

Each C line of code corresponds perfectly with its line in the assembly: http://goo.gl/DZigfX每行 C 代码都与它在程序集中的行完美对应: http : //goo.gl/DZigfX

Each of those instructions are extremely fast , so the function is extremely fast too.这些指令中的每一条都非常快,因此该功能也非常快。 Since the code is so small and quick, it might be useful to inline the function when using it.由于代码又小又快,所以在使用时inline函数可能很有用。


Credit:信用:

I'm using:我正在使用:

template <class _Ty>
inline _Ty n_Align_Up(_Ty n_x, _Ty n_alignment)
{
    assert(n_alignment > 0);
    //n_x += (n_x >= 0)? n_alignment - 1 : 1 - n_alignment; // causes to round away from zero (greatest absolute value)
    n_x += (n_x >= 0)? n_alignment - 1 : -1; // causes to round up (towards positive infinity)
    //n_x += (_Ty(-(n_x >= 0)) & n_alignment) - 1; // the same as above, avoids branch and integer multiplication
    //n_x += n_alignment - 1; // only works for positive numbers (fastest)
    return n_x - n_x % n_alignment; // rounds negative towards zero
}

and for powers of two:并为二的权力:

template <class _Ty>
bool b_Is_POT(_Ty n_x)
{
    return !(n_x & (n_x - 1));
}

template <class _Ty>
inline _Ty n_Align_Up_POT(_Ty n_x, _Ty n_pot_alignment)
{
    assert(n_pot_alignment > 0);
    assert(b_Is_POT(n_pot_alignment)); // alignment must be power of two
    -- n_pot_alignment;
    return (n_x + n_pot_alignment) & ~n_pot_alignment; // rounds towards positive infinity (i.e. negative towards zero)
}

Note that both of those round negative values towards zero (that means round to positive infinity for all values), neither of them relies on signed overflow (which is undefined in C/C++).请注意,这两个负值都向零舍入(这意味着将所有值舍入到正无穷大),它们都不依赖于有符号溢出(在 C/C++ 中未定义)。

This gives:这给出:

n_Align_Up(10, 100) = 100
n_Align_Up(110, 100) = 200
n_Align_Up(0, 100) = 0
n_Align_Up(-10, 100) = 0
n_Align_Up(-110, 100) = -100
n_Align_Up(-210, 100) = -200
n_Align_Up_POT(10, 128) = 128
n_Align_Up_POT(130, 128) = 256
n_Align_Up_POT(0, 128) = 0
n_Align_Up_POT(-10, 128) = 0
n_Align_Up_POT(-130, 128) = -128
n_Align_Up_POT(-260, 128) = -256

may be this can help:也许这可以帮助:

int RoundUpToNearestMultOfNumber(int val, int num)
{
  assert(0 != num);
  return (floor((val + num) / num) * num);
}

To always round up总是四舍五入

int alwaysRoundUp(int n, int multiple)
{
    if (n % multiple != 0) {
        n = ((n + multiple) / multiple) * multiple;

        // Another way
        //n = n - n % multiple + multiple;
    }

    return n;
}

alwaysRoundUp(1, 10) -> 10 alwaysRoundUp(1, 10) -> 10

alwaysRoundUp(5, 10) -> 10 alwaysRoundUp(5, 10) -> 10

alwaysRoundUp(10, 10) -> 10 alwaysRoundUp(10, 10) -> 10


To always round down总是四舍五入

int alwaysRoundDown(int n, int multiple)
{
    n = (n / multiple) * multiple;

    return n;
}

alwaysRoundDown(1, 10) -> 0 alwaysRoundDown(1, 10) -> 0

alwaysRoundDown(5, 10) -> 0 alwaysRoundDown(5, 10) -> 0

alwaysRoundDown(10, 10) -> 10 alwaysRoundDown(10, 10) -> 10


To round the normal way以正常方式圆

int normalRound(int n, int multiple)
{
    n = ((n + multiple/2)/multiple) * multiple;

    return n;
}

normalRound(1, 10) -> 0 normalRound(1, 10) -> 0

normalRound(5, 10) -> 10 normalRound(5, 10) -> 10

normalRound(10, 10) -> 10 normalRound(10, 10) -> 10

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

int noOfMultiples = int((numToRound / multiple)+0.5);
return noOfMultiples*multiple

C++ rounds each number down,so if you add 0.5 (if its 1.5 it will be 2) but 1.49 will be 1.99 therefore 1. C++ 将每个数字向下舍入,因此如果添加 0.5(如果它是 1.5,它将是 2)但 1.49 将是 1.99 因此是 1。

EDIT - Sorry didn't see you wanted to round up, i would suggest using a ceil() method instead of the +0.5编辑 - 抱歉没有看到你想要四舍五入,我建议使用 ceil() 方法而不是 +0.5

well for one thing, since i dont really understand what you want to do, the lines一方面,因为我真的不明白你想做什么,线条

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

could definitely be shortened to绝对可以缩短为

int roundUp = roundDown + multiple;
return roundUp;

Round to nearest multiple that happens to be a power of 2四舍五入到恰好是 2 的幂的最接近的倍数

unsigned int round(unsigned int value, unsigned int multiple){
    return ((value-1u) & ~(multiple-1u)) + multiple;
}

This can be useful for when allocating along cachelines, where the rounding increment you want is a power of two, but the resulting value only needs to be a multiple of it.这对于沿缓存线分配时很有用,其中您想要的舍入增量是 2 的幂,但结果值只需要是它的倍数。 On gcc the body of this function generates 8 assembly instructions with no division or branches.gcc上,这个函数的主体生成 8 条没有除法或分支的汇编指令。

round(  0,  16) ->   0
round(  1,  16) ->  16
round( 16,  16) ->  16
round(257, 128) -> 384 (128 * 3)
round(333,   2) -> 334

For negative numToRound:对于负 numToRound:

It should be really easy to do this but the standard modulo % operator doesn't handle negative numbers like one might expect.这样做应该很容易,但标准的模 % 运算符并不能像人们期望的那样处理负数。 For instance -14 % 12 = -2 and not 10. First thing to do is to get modulo operator that never returns negative numbers.例如 -14 % 12 = -2 而不是 10。首先要做的是获得永远不会返回负数的模运算符。 Then roundUp is really simple.那么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);
}

This is what I would do:这就是我会做的:

#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;
}

The code might not be optimal, but I prefer clean code than dry performance.代码可能不是最佳的,但我更喜欢干净的代码而不是干性能。

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

although:虽然:

  • won't work for negative numbers不适用于负数
  • won't work if numRound + multiple overflows如果 numRound + 多次溢出将不起作用

would suggest using unsigned integers instead, which has defined overflow behaviour.建议改用无符号整数,它定义了溢出行为。

You'll get an exception is multiple == 0, but it isn't a well-defined problem in that case anyway.你会得到一个异常是 multiple == 0,但无论如何在这种情况下它不是一个明确定义的问题。

c: C:

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

and for your ~/.bashrc:和你的 ~/.bashrc:

roundup()
{
  echo $(( ${2} ? ((${1}+${2}-1)/${2})*${2} : ${1} ))
}

I use a combination of modulus to nullify the addition of the remainder if x is already a multiple:如果x已经是倍数,我使用模数的组合来抵消余数的添加:

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

We find the inverse of the remainder then modulus that with the divisor again to nullify it if it is the divisor itself then add x .我们找到余数的倒数,然后再次用除数取模以使其无效,如果它是除数本身,则添加x

round_up(19, 3) = 21

I found an algorithm which is somewhat similar to one posted above:我发现了一种与上面发布的算法有些相似的算法:

int[(|x|+n-1)/n]*[(nx)/|x|], where x is a user-input value and n is the multiple being used. int[(|x|+n-1)/n]*[(nx)/|x|],其中 x 是用户输入值,n 是使用的倍数。

It works for all values x, where x is an integer (positive or negative, including zero).它适用于所有值 x,其中 x 是一个整数(正数或负数,包括零)。 I wrote it specifically for a C++ program, but this can basically be implemented in any language.我是专门为 C++ 程序编写的,但这基本上可以用任何语言实现。

Here's my solution based on the OP's suggestion, and the examples given by everyone else.这是我基于 OP 的建议以及其他人给出的示例的解决方案。 Since most everyone was looking for it to handle negative numbers, this solution does just that, without the use of any special functions, ie abs, and the like.由于大多数人都在寻找它来处理负数,因此该解决方案就是这样做的,而无需使用任何特殊函数,即 abs 等。

By avoiding the modulus and using division instead, the negative number is a natural result, although it's rounded down.通过避免模数并使用除法,负数是一个自然的结果,尽管它被四舍五入了。 After the rounded down version is calculated, then it does the required math to round up, either in the negative or positive direction.在计算向下舍入的版本后,它会执行所需的数学运算以向上或向负方向向上舍入。

Also note that no special functions are used to calculate anything, so there is a small speed boost there.还要注意,没有使用特殊函数来计算任何东西,所以那里有一个小的速度提升。

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;
}

I think this should help you.我想这应该对你有帮助。 I have written the below program in C.我已经用 C 编写了以下程序。

# include <stdio.h>
int main()
{
  int i, j;
  printf("\nEnter Two Integers i and j...");
  scanf("%d %d", &i, &j);
  int Round_Off=i+j-i%j;
  printf("The Rounded Off Integer Is...%d\n", Round_Off);
  return 0;
}

Endless possibilities, for signed integers only:无限的可能性,仅适用于有符号整数:

n + ((r - n) % r) n + ((r - n) % r)

/// Rounding up 'n' to the nearest multiple of number 'b'.
/// - Not tested for negative numbers.
/// \see http://stackoverflow.com/questions/3407012/
#define roundUp(n,b) ( (b)==0 ? (n) : ( ((n)+(b)-1) - (((n)-1)%(b)) ) )

/// \c test->roundUp().
void test_roundUp() {   
    // yes_roundUp(n,b) ( (b)==0 ? (n) : ( (n)%(b)==0 ? n : (n)+(b)-(n)%(b) ) )
    // yes_roundUp(n,b) ( (b)==0 ? (n) : ( ((n + b - 1) / b) * b ) )

    // no_roundUp(n,b) ( (n)%(b)==0 ? n : (b)*( (n)/(b) )+(b) )
    // no_roundUp(n,b) ( (n)+(b) - (n)%(b) )

if (true) // couldn't make it work without (?:)
{{  // test::roundUp()
    unsigned m;
                { m = roundUp(17,8); } ++m;
    assertTrue( 24 == roundUp(17,8) );
                { m = roundUp(24,8); }
    assertTrue( 24 == roundUp(24,8) );

    assertTrue( 24 == roundUp(24,4) );
    assertTrue( 24 == roundUp(23,4) );
                { m = roundUp(23,4); }
    assertTrue( 24 == roundUp(21,4) );

    assertTrue( 20 == roundUp(20,4) );
    assertTrue( 20 == roundUp(19,4) );
    assertTrue( 20 == roundUp(18,4) );
    assertTrue( 20 == roundUp(17,4) );

    assertTrue( 17 == roundUp(17,0) );
    assertTrue( 20 == roundUp(20,0) );
}}
}

This is getting the results you are seeking for positive integers:这得到了您正在寻找的正整数的结果:

#include <iostream>
using namespace std;

int roundUp(int numToRound, int multiple);

int main() {
    cout << "answer is: " << roundUp(7, 100) << endl;
    cout << "answer is: " << roundUp(117, 100) << endl;
    cout << "answer is: " << roundUp(477, 100) << endl;
    cout << "answer is: " << roundUp(1077, 100) << endl;
    cout << "answer is: " << roundUp(52,20) << endl;
    cout << "answer is: " << roundUp(74,30) << endl;
    return 0;
}

int roundUp(int numToRound, int multiple) {
    if (multiple == 0) {
        return 0;
    }
    int result = (int) (numToRound / multiple) * multiple;
    if (numToRound % multiple) {
        result += multiple;
    } 
    return result;
}

And here are the outputs:这是输出:

answer is: 100
answer is: 200
answer is: 500
answer is: 1100
answer is: 60
answer is: 90

I think this works:我认为这有效:

int roundUp(int numToRound, int multiple) {
    return multiple? !(numToRound%multiple)? numToRound : ((numToRound/multiple)+1)*multiple: numToRound;
}

This works for me but did not try to handle negatives这对我有用,但没有尝试处理底片

public static int roundUp(int numToRound, int multiple) {
    if (multiple == 0) {
        return 0;
    } else if (numToRound % multiple == 0) {
    return numToRound;
    }

    int mod = numToRound % multiple;
    int diff = multiple - mod;
    return numToRound + diff;
}

Here is a super simple solution to show the concept of elegance.这里有一个超级简单的解决方案来展示优雅的概念。 It's basically for grid snaps.它基本上用于网格捕捉。

(pseudo code) (伪代码)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM