Python:(8%3)的结果是2,但是( - 8%3)是1.不应该是-2吗?为什么?

use*_*688 4 python

这是证明:

-8 == -2 * 3 - 2
Run Code Online (Sandbox Code Playgroud)

这意味着-8%3应该等于-2.但是python回归1并且它让我疯狂

wim*_*wim 10

在python中,符号与分母匹配.

>>> -8 % 3
1
>>> -8 % -3
-2
Run Code Online (Sandbox Code Playgroud)

有关为何以这种方式实现的解释,请阅读Guido的博客文章.


mhl*_*ter 5

整数数学很有趣:

>>> -8//3  # (-8/3 in python2 does the same thing)
-3
>>> 8//3   # (8/3 in python2 does the same thing)
2
>>>
Run Code Online (Sandbox Code Playgroud)

舍入做下来,不会接近零.