Recognizing when to use the modulus operator

前端 未结 19 985
醉梦人生
醉梦人生 2020-11-29 16:40

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?

I know I can u

19条回答
  •  清歌不尽
    2020-11-29 16:53

    Often, in a loop, you want to do something every k'th iteration, where k is 0 < k < n, assuming 0 is the start index and n is the length of the loop.

    So, you'd do something like:

    int k = 5;
    int n = 50;
    for(int i = 0;i < n;++i)
    {
        if(i % k == 0)  // true at 0, 5, 10, 15..
        {
            // do something
        }
    }
    

    Or, you want to keep something whitin a certain bound. Remember, when you take an arbitrary number mod something, it must produce a value between 0 and that number - 1.

提交回复
热议问题