Rounding off a positive number to the next nearest multiple of 5

int mod = grades[j] % 5;
int round = grades[j] - mod;
if (mod > 0) {
    round += 5;
}

You can take the difference between grades[j] and the next number, and just add it. For example, if grades[j] == 12 then 12 mod 5 == 2, so add 5 - 2.

Here is a sample program to test it out:

#include <iostream>

int main() {
    int x[] = {2,7,123,32}; // some random numbers to show how this works
    for (int i = 0; i < 4; {
        std::cout << x[i] << "\t" << x[i] + ((5-(x[i] % 5)) % 5) << std::endl;
    }
    return 0;
}

Output:

2   5
7   10
123 125
32  35

To round up the general form should be:

((n + denominator -1) / denominator )* denominator 

so in your case:

int round = ((grades[j] + 4)/5) * 5;

The reason we deduct 1 from the denominator is to handle exact multiples of the rounding value for instance:

((70 + 4) / 5) * 5

would yield 70


This is my solution using cmath::abs

int rounded = n + abs((n % denom) - denom);

You can change the denom with any other denomination you want

Tags:

C++