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

Viewed 19901

I need to round of a number (the input is guaranteed to be an integer & is positive) to the next multiple of 5.

I tried this:

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

However, this rounds off the number to the nearest multiple of 5.

Eg: 67 is rounded off to 65, not 70.

8 Answers

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

I have a function to round up:

def next(number, base):
    temp = round(number / base) * base
    return temp

you can use it for your case like this:

next(grade[j], 5)

and in function it will be:

temp = round(67 / 5) * 5
return temp #temp = 75

some case not using round but using ceil

Why so much of complication. Here is the code. Have a look.

vector<int> gradingStudents(vector<int> grades) {
    int size = grades.size();
    for(int i=0;i<size;i++)
    {
        if(grades[i]>40)
        {
            if((grades[i]+2)%5==0)
            grades[i]=grades[i]+2;
            else if((grades[i]+1)%5==0)
            grades[i]=grades[i]+1;
        }
        else if(grades[i]>37&&grades[i]<40)
        grades[i]=40;
    }
return grades;
}
Related