使用带有整数的模运算符

时间:2014-08-25 15:38:14

标签: modulo

我正在尝试计算模运算1 % 32如何等于12 % 32等于2,依此类推。

我有这段代码:

 uint8_t value;

  for (uint16_t i = 0; i < 64; i++) {

    value = (i % 32);

    Serial.println(value);
  }

我得到的结果是:

  

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

i等于0i等于32时,我可以看到逻辑。例如,如果我们采用后者的其余部分:32 / 32我们得到0。但是,对于131范围内的所有数字,我似乎无法得到与该程序相同的答案。例如,如果我将整数1除以32以获得余数,我只需0。这与2, 3, 4, 5, 6, n,..

相同

我必须在这里找到一些东西。

1 个答案:

答案 0 :(得分:1)

modulo operation的结果是余数:

0 divided by 32 equals 0 with a remainder of 0
1 divided by 32 equals 0 with a remainder of 1
2 divided by 32 equals 0 with a remainder of 2
3 divided by 32 equals 0 with a remainder of 3
4 divided by 32 equals 0 with a remainder of 4
5 divided by 32 equals 0 with a remainder of 5

...

29 divided by 32 equals 0 with a remainder of 29
30 divided by 32 equals 0 with a remainder of 30
31 divided by 32 equals 0 with a remainder of 31
32 divided by 32 equals 1 with a remainder of 0
33 divided by 32 equals 1 with a remainder of 1
34 divided by 32 equals 1 with a remainder of 2
35 divided by 32 equals 1 with a remainder of 3
36 divided by 32 equals 1 with a remainder of 4
37 divided by 32 equals 1 with a remainder of 5
38 divided by 32 equals 1 with a remainder of 6
39 divided by 32 equals 1 with a remainder of 7
...

所以你看到的结果是你应该期待的。考虑2 % 32。 &#34; 2除以32等于0,余数为2 &#34;。所以2 % 32 == 2