模数如何工作以及为什么它在 Python 中与大多数语言不同?
下面是一些 C++ 代码。如果你在 python 中尝试类似 -2%5
的结果,结果是正 3,而许多其他语言,如 c++ C# (代码) 和 flash 给出 -2
为什么他们给出 -2 并且一个版本比另一个版本更正确?
#include <cstdio>
int main(){
printf("%d\n", 2%5);
printf("%d\n", -2%5);
printf("%d\n", -2%77);
printf("%d\n", 2%-77);
printf("%d\n", -2%-77);
}
输出:
2
-2
-2
2
-2
Below is some code in C++. If you try something like -2%5
in python the result is positive 3 while many other languages like c++ C# (code) and flash give -2
Why do they give -2 and is one version more correct than the other?
#include <cstdio>
int main(){
printf("%d\n", 2%5);
printf("%d\n", -2%5);
printf("%d\n", -2%77);
printf("%d\n", 2%-77);
printf("%d\n", -2%-77);
}
Output:
2
-2
-2
2
-2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
r = a % n
,则对于某些q
,a = n * q + r
。这意味着您对r
的值有多种选择,具体取决于所选择的q
的值。我建议阅读 http://en.wikipedia.org/wiki/Modulo_operation,其中写着大多数编程语言选择
r
和-n
r < n
。这意味着,除非 r 为零,否则 r 的值有两种选择 - 一种是正数,一种是负数。不同的编程语言对于采用正数还是负数做出不同的决定。您会在该页面上找到一个表格,总结了不同语言的功能:n
具有相同符号的r
(这就是您在上面看到的)。a
符号相同的r
(在 2011 标准之前,它是实现定义的)。如果你想确保在 Python 中得到正数,请使用以下命令:
If
r = a % n
, thena = n * q + r
for someq
. That means that you have many choices for the value ofr
, depending on the value ofq
that gets chosen.I'd recommend reading http://en.wikipedia.org/wiki/Modulo_operation, which says that most programming languages choose
r
with-n < r < n
. That means that, unlessr
is zero, you have two choices for the value ofr
- one positive, one negative. Different programming languages make different decisions about whether to take the positive or negative one. You'll find a table on that page that summarizes what different languages do:r
with the same sign asn
(which is what you see above).r
with the same sign asa
(and before the 2011 standard, it's implementation defined).If you want to be sure that you get the positive one in Python, use this:
根据 C++ 文档:
这看起来很奇怪。 Python 文档仅说明了这一点:
在我看来,Python 方式更符合逻辑,但这只是一种直觉。
According to the C++ documentation:
Which seems odd. The Python documentation says only this:
It seems to me that the Python way is more logical, but that's just a gut feeling.
我想你应该看看下面的内容。除了使用稍微不同的算法之外,运算符优先级也很重要。尝试使用括号:
I think you should look at the below. In addition to using slightly different algorithms, operator precedence matters. Try it with brackets: