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 = ((grade
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
int mod = grades[j] % 5;
int round = grades[j] - mod;
if (mod > 0) {
round += 5;
}
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
Try this:
int num = grades[j] % 5 < 3 ? grades[j] - (grades[j] % 5) : grades[j] - (grades[j] % 5) + 5;
Here demo code:
#include <stdio.h>
int main() {
//code
int grades[5] = {10, 68, 12, 67, 41};
int j;
for (j = 0; j < 5; j++)
{
int num = grades[j] % 5 < 3? grades[j] - (grades[j] % 5) : grades[j] - (grades[j] % 5) + 5;
printf("%d\n",num);
}
return 0;
}
Output:
10
70
10
65
40
I hope help you.
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
One algorithm that works is:
In code:
int round(int nearest , int number){
int half = nearest / 2;
int answer = 0;
int remainder = number% nearest ;
int quotient = number/ nearest ;
if(remainder > half ){
answer =(quotient+1) * nearest ;
}else{
answer =quotient * nearest ;
}
return answer;
}