Home > Backend Development > C++ > How can I efficiently round up an integer to the nearest multiple in C ?

How can I efficiently round up an integer to the nearest multiple in C ?

DDD
Release: 2024-11-25 14:21:12
Original
388 people have browsed it

How can I efficiently round up an integer to the nearest multiple in C  ?

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;
    }
}
Copy after login

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:

  • roundUp(7, 100) → 100
  • roundUp(117, 100) → 200
  • roundUp(477, 100) → 500
  • roundUp(52, 20) → 60
  • roundUp(74, 30) → 90

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template