Python模数函数

时间:2017-04-27 22:19:47

标签: python-3.x modulo

据我所知,Modulo函数返回除法问题的其余部分。 例如:16%5 = 3,余数为1.因此将返回1。

>>> 1 % 3      Three goes into 1 zero times remainder 1
1
>>> 2 % 3      Three goes into 2 zero times remainder 2
2
>>> 0 % 3      What happens here?  3 goes into zero, zero times remainder 3 

如果我们遵循前两个插图的逻辑,那不是返回的,零是。为什么呢?

>>> 0 % 3 
0

2 个答案:

答案 0 :(得分:1)

定义了Python %运算符,以便x % y == x - (x // y) * y,其中x // y =⌊x/y⌋。对于正整数,这对应于除法的“余数”的通常概念。所以,对于任何y≠0,

0 % y
= 0 - ⌊0 / y⌋ * y      by definition of %
= 0 - ⌊0⌋ * y          because 0 divided by anything is 0
= 0 - 0 * y            because 0 is an integer, so floor leaves it unchanged
= 0 - 0                because 0 times anything is 0
= 0

答案 1 :(得分:0)

再次查看:

1 % 3 is 0 remainder 1 =>  1 = 3*0 + 1  
2 % 3 is 0 remainder 2 =>  2 = 3*0 + 2
0 % 3 is 0 remainder 0 [not 3] because 0 = 3*0 + 0

在前两种情况下,为什么要分配除后的剩余物,而不是最后一种?