%在计算中是什么?我不知道它是做什么的。

它能算出计算的百分比吗例如4% 2显然等于0。如何?


当前回答

我发现掌握模运算符(%)最简单的方法是通过长除法。它是余数,在确定一个数是偶数还是奇数时很有用:

4%2 = 0

  2
2|4
 -4
  0


11%3 = 2

  3
3|11
 -9
  2

其他回答

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

摘自http://docs.python.org/reference/expressions.html

示例1: 6%2的结果为0,因为如果6除以2,没有余数(3倍)。

例2:7%2的结果是1,因为当7除以2(3次)时,余数是1。

总结一下,它返回除法运算的余数,如果没有余数,则返回0。6%2意味着6的余数除以2。

模运算符,通常用于整数的余数除法,但在Python中可用于浮点数。

http://docs.python.org/reference/expressions.html

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

我发现掌握模运算符(%)最简单的方法是通过长除法。它是余数,在确定一个数是偶数还是奇数时很有用:

4%2 = 0

  2
2|4
 -4
  0


11%3 = 2

  3
3|11
 -9
  2

此外,还有一个有用的内置函数divmod:

divmod (a, b) 取两个(非复数)数字作为参数并返回一对数字 由它们的商和组成 使用长除法时的余数。

模数-左手操作数除以右手操作数并返回余数。

如果有帮助的话:

1:0> 2%6
=> 2
2:0> 8%6
=> 2
3:0> 2%6 == 8%6
=> true

... 等等。