How does the modulus operator work?

前端 未结 5 1659
忘了有多久
忘了有多久 2020-11-27 17:19

Let\'s say that I need to format the output of an array to display a fixed number of elements per line. How do I go about doing that using modulus operation?

Using C

5条回答
  •  一向
    一向 (楼主)
    2020-11-27 17:58

    in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:

    5 % 2 = 1
    13 % 5 = 3
    

    With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).

    To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).

提交回复
热议问题