Python 中 % 的结果是什么? [英] What is the result of % in Python?
问题描述
计算中的 %
是什么?我似乎无法弄清楚它的作用.
What does the %
in a calculation? I can't seem to work out what it does.
它是否计算出百分比的计算,例如:4 % 2
显然等于 0.如何?
Does it work out a percent of the calculation for example: 4 % 2
is apparently equal to 0. How?
推荐答案
%(模)运算符产生第一个参数除以第二个参数的余数.数字参数首先转换为通用类型.零右参数引发 ZeroDivisionError 异常.参数可以是浮点数,例如,3.14%0.7 等于 0.34(因为 3.14 等于 4*0.7 + 0.34.)模运算符总是产生与它的第二个操作数(或零)具有相同符号的结果;结果的绝对值严格小于第二个操作数[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 次),则没有余数.
Example 1:
6%2
evaluates to 0
because there's no remainder if 6 is divided by 2 ( 3 times ).
示例 2:7%2
的计算结果为 1
,因为当 7 相除时,还有 1
的余数按 2(3 次).
Example 2: 7%2
evaluates to 1
because there's a remainder of 1
when 7 is divided by 2 ( 3 times ).
总而言之,它返回除法运算的余数,如果没有余数,则返回 0
.所以 6%2
表示求 6 除以 2 的余数.
So to summarise that, it returns the remainder of a division operation, or 0
if there is no remainder. So 6%2
means find the remainder of 6 divided by 2.
这篇关于Python 中 % 的结果是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!