Rounding Integers Up to Multiples
In C , rounding an integer value up to the nearest multiple of another number is a straightforward operation. The following function accomplishes this task efficiently and accurately:
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; } }
This function takes two integer arguments: the value to be rounded (numToRound) and the multiple to round it up to (multiple). It returns the rounded-up value as an integer.
The function first checks if the multiple is zero. If it is, the function returns the original value unchanged.
If the multiple is not zero, the function computes the absolute value of the remainder of dividing numToRound by multiple. This gives the difference between the original value and the nearest multiple below it.
Next, the function checks if the original value is negative. If it is, it adjusts the rounded-up value accordingly to ensure it is still greater than or equal to the original value. For positive values, the function simply adds the necessary amount to round up to the nearest multiple.
Examples
Consider the following examples:
In each case, the function correctly rounds the original value up to the nearest multiple of the given multiple.
The above is the detailed content of How can I efficiently round up an integer to the nearest multiple in C ?. For more information, please follow other related articles on the PHP Chinese website!