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

前端 未结 7 740
我寻月下人不归
我寻月下人不归 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: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

提交回复
热议问题