为什么负数的模数为正(-7%6 == 5)? [英] Why is modulo of a negative number positive (-7 % 6 == 5)?
问题描述
为什么以下是正确的?
print(-7 % 6 == 5);
这意味着-7 % 6
会产生 5
,但是我会期望看到-1
(在JavaScript中就是这种情况).
This means that -7 % 6
yields 5
, but I would expect to see -1
(in JavaScript this is the case).
推荐答案
Dart中的模数行为与JavaScript,C,C ++等中的行为不同.它与Python共享其行为,关于此主题,有一个在此处有很好答案的问题.
The modulo behavior in Dart is different from the behavior in JavaScript, C, C++, and others. It shares its behavior with Python and about this topic there is a question with great answers here.
在@kennytm的出色的答案上加了一点,对此的直观解释是,它的作用类似于肯定的因式分解(至少在Dart中如此):
Adding a bit to the superb answer by @kennytm, the intuitive explanation for this is that it works analogous to positive factorisation (at least in Dart):
17 % 6 == 5 <=> -7 % 6 == 5
(2 * 6 + 5) % 6 == 5 <=> (-2 * 6 + 5) % 6 == 5
但是,它可以很容易地以不同的方式合理地实施,但这就是Dart中的工作方式.
However, it could have easily been implemented differently, reasonably, but this is how it works in Dart.
以下是一个好处(引用自前面提到的答案):
A benefit of this is the following (quote from the answer mentioned earlier):
选择它来代替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
这篇关于为什么负数的模数为正(-7%6 == 5)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!