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

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

    Try this:

    int num = grades[j] % 5 < 3 ? grades[j] - (grades[j] % 5) : grades[j] - (grades[j] % 5) + 5;
    

    Here demo code:

    #include 
    
    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.

提交回复
热议问题