整数除法(%)Python中是否有错误?

问题描述 投票:0回答:3

win32上的[Python 3.7.4(tags / v3.7.4:e09359112e,2019年7月8日,20:34:20)[MSC v.1916 64位(AMD64)]]输入“帮助”,“版权”,“信用”或“许可证”以获取更多信息。

7%528%536%51

integer-division
3个回答
1
投票

部门/

使用整数作为输入,该除法将为您提供整数结果(Python2 +

>>> 7/5
1
>>> 8/5
1
>>> 10/5
2

至少使用一个非整数作为输入(Python2 +),您将得到一个非整数结果。

>>> 10/1.5
6.666666666666667
>>> 10/4.0
2.5

Python3:整数除法为//

>>> 10/4 # Python 3
2.5
>>> 10//4 # Python 3 integer division
2

模数%(=余数)

模是整数除法的余数

>>> 7%5 # = What is the remainder of the division of 7 by 5
2
>>> 8%5
3
>>> 10%5
0

0
投票

这不是除法,而是Modulo(它为您提供余数)。您应该使用/而不是%


0
投票

您正在使用模数运算7%5 = 2,其正确对于整数除法,您必须使用“ //”,例如:7//5。如果要进行浮点运算,则可以使用7/5

© www.soinside.com 2019 - 2024. All rights reserved.