我在Python中发现了一些有关负数的奇怪行为:
I've found some strange behaviour in Python regarding negative numbers:
>>> -5 % 4 3谁能解释发生了什么事?
Could anyone explain what's going on?
推荐答案与C或C ++不同,Python的模运算符(%)始终返回与分母(除数)符号相同的数字.您的表情之所以产生3,是因为
Unlike C or C++, Python's modulo operator (%) always return a number having the same sign as the denominator (divisor). Your expression yields 3 because
(-5)/4 = -1.25->下限(-1.25)= -2
(-5) / 4 = -1.25 --> floor(-1.25) = -2
(-5)%4 =(-2× 4 + 3)%4 = 3.
(-5) % 4 = (-2 × 4 + 3) % 4 = 3.
选择它来代替C行为,因为非负结果通常更有用.一个示例是计算工作日.如果今天是星期二(第2天),那么前 N 天是星期几?在Python中,我们可以使用
It is chosen over the C behavior because a nonnegative result is often more useful. An example is to compute week days. If today is Tuesday (day #2), what is the week day N days before? In Python we can compute with
return (2 - N) % 7但是在C中,如果 N ≥3,我们得到一个负数,它是无效数字,我们需要通过添加7来手动对其进行修正:
but in C, if N ≥ 3, we get a negative number which is an invalid number, and we need to manually fix it up by adding 7:
int result = (2 - N) % 7; return result < 0 ? result + 7 : result;(请参阅 en.wikipedia/wiki/Modulo_operator 确定了不同语言的结果符号.)
(See en.wikipedia/wiki/Modulo_operator for how the sign of result is determined for different languages.)
更多推荐
Python中对负数的取模运算
发布评论