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

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

    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, so add 5 - 2.

    Here is a sample program to test it out:

    #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
    
    0 讨论(0)
提交回复
热议问题