Dou*_* AA 13 python math modular
我想在x中添加一个数字y,但是要将x换行保持在0到48之间.注意y可能是负数但是永远不会有大于48的数量.有没有比这更好的方法:
x = x + y
if x >= 48:
x = x - 48
elif x < 0:
x = x + 48
Run Code Online (Sandbox Code Playgroud)
?
nmi*_*els 18
x = (x + y) % 48
Run Code Online (Sandbox Code Playgroud)
模运算符是你的朋友.
>>> 48 % 48
0: 0
>>> 49 % 48
1: 1
>>> -1 % 48
2: 47
>>> -12 % 48
3: 36
>>> 0 % 48
4: 0
>>> 12 % 48
5: 12
Run Code Online (Sandbox Code Playgroud)