Rounds a number to the next nearest multiple of 5
5 answers
To round off the general shape, there should be:
((n + denominator -1) / denominator )* denominator
so in your case:
int round = ((grades[j] + 4)/5) * 5;
The reason we subtract 1 from the denominator is to handle exact multiples of the rounding values, for example:
((70 + 4) / 5) * 5
will give 70
+6
source to share
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
, add 5 - 2
.
Here's a sample program for testing:
#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
+5
source to share
Try the following:
int num = grades[j] % 5 < 3 ? grades[j] - (grades[j] % 5) : grades[j] - (grades[j] % 5) + 5;
Here's a 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 to help you.
0
source to share
One of the algorithms:
- half round value
- get the remainder of the number by dividing it by roundValue
- get the division ratio (so we can reproduce with it at the end)
- comparing it to Half Round Value
- , if it is more than half of it, it is rounded to the nearest higher value
- if it is less than half of its rounding to the nearest lower value
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;
}
-1
source to share