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

前端 未结 7 734
我寻月下人不归
我寻月下人不归 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 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;
            }
    

提交回复
热议问题