gpt4 book ai didi

flutter - 为什么负数的模数为正(-7%6 == 5)?

转载 作者:行者123 更新时间:2023-12-03 02:50:33 25 4
gpt4 key购买 nike

为什么以下说法是正确的?

print(-7 % 6 == 5);

这意味着 -7 % 6会产生 5 ,但我会 期望看到 -1(在JavaScript中就是这种情况)。

Proof in DartPad

最佳答案

Dart中的模态行为不同于JavaScript,C,C++等中的行为。它与Python共享其行为,有关此主题,有一个question with great answers here
模数在Dart中始终为正数。

superb answer by @kennytm上增加了一点,对此的直观解释是它的工作类似于正因式分解(至少在Dart中如此):

17 % 6 == 5          <=> -7 % 6 == 5
(2 * 6 + 5) % 6 == 5 <=> (-2 * 6 + 5) % 6 == 5
但是,可以很容易地以不同的方式合理地实现它,但这就是Dart中的工作方式。
这样做的好处是以下内容(来自 the answer mentioned earlier的引用):

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

关于flutter - 为什么负数的模数为正(-7%6 == 5)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59470362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com