Incrementing a variable in a cycle (modulo)

ぃ、小莉子 提交于 2019-12-11 13:03:51

问题


I wish to cycle the values of a variable (call it x) through the pattern 0, 1, 2, 0, 1, 2, … upon activation of a function (call it update). I've managed to get 1, 2, 0, 1, 2, 0, … by doing:

var x = 0;

function update() {
  x = ++x % 3;
}

Then I tried the post-increment operator instead, and the value of x just remains at 0:

var x = 0;

function update() {
  x = x++ % 3;
}

Then the more I thought about this code, the more confused I got. I think 0 modulo 3 is being done first, then the assignment (of 0) to x, but then is x not incremented to 1? (it seems that it isn't, but that's not what I want anyway — I want the pattern to start at 0. Can someone explain what's going on with this code and how to achieve the pattern starting at 0?


回答1:


Your second example of code is doing this

  1. Store the old value of x
  2. Increment x
  3. Modulo the old value of x by 3
  4. Store the result of the modulus in x

Your first code should give you the correct solution if you call it like this:

look_at_value()
update()
look_at_value()
update()
...

If you want to call update before looking at the value, you will need to initialize x = -1 (or 2 mod 3)

Clearer code would be:

function update() {
    x = (x+1) % 3;
}


来源:https://stackoverflow.com/questions/33635039/incrementing-a-variable-in-a-cycle-modulo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!