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

前端 未结 7 723
我寻月下人不归
我寻月下人不归 2020-12-11 03:39

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         


        
相关标签:
7条回答
  • 2020-12-11 03:53

    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

    0 讨论(0)
  • 2020-12-11 03:58
    int mod = grades[j] % 5;
    int round = grades[j] - mod;
    if (mod > 0) {
        round += 5;
    }
    
    0 讨论(0)
  • 2020-12-11 04:04

    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

    0 讨论(0)
  • 2020-12-11 04:09

    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.

    0 讨论(0)
  • 2020-12-11 04:12

    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

    0 讨论(0)
  • 2020-12-11 04:14

    One algorithm that works is:

    1. half the round value
    2. get the remainder of number by dividing it with roundValue
    3. get quotient of division (so that we can multiply with it in end)
    4. comparing it with the half of round Value
    5. if it's greater than half it rounds to the nearest greater value
    6. if it's less than half it rounds to the nearest smaller 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;
            }
    
    0 讨论(0)
提交回复
热议问题