Home > Backend Development > C++ > How to Efficiently Round Up Numbers to the Nearest Multiple in C ?

How to Efficiently Round Up Numbers to the Nearest Multiple in C ?

Linda Hamilton
Release: 2024-12-02 01:38:13
Original
185 people have browsed it

How to Efficiently Round Up Numbers to the Nearest Multiple in C  ?

Rounding Numbers Up to the Nearest Multiple in C

Rounding numbers up to the nearest multiple is a fundamental operation in programming. In C , it can be achieved using straightforward integer math.

Simple Rounding Up Algorithm

The initial algorithm checks for a multiple of 0, returning the original number in that case. Otherwise, it calculates the rounded-down value and adds the multiple to it. This approach, however, only works for positive numbers.

Improved Rounding Algorithm

To address the issue of negative numbers, a more robust algorithm is required. This improved version utilizes the absolute value of the number and ensures that the rounded result is always greater than or equal to the input.

Implementation:

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 algorithm handles both positive and negative numbers correctly, providing the expected rounded-up values as specified in the examples provided.

The above is the detailed content of How to Efficiently Round Up Numbers 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template