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

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


当前回答

X % y计算除法X除以y的余数,其中商为整数。余数是y的符号。


在Python 3上,计算结果为6.75;这是因为/做的是真除法,而不是像Python 2中那样(默认情况下)的整数除法。在Python 2上,1 / 4给出0,因为结果是四舍五入。

整数除法也可以在python3上执行,使用//操作符,因此要得到7,你可以执行:

3 + 2 + 1 - 5 + 4 % 2 - 1 // 4 + 6

此外,在python2中,只需添加该行,就可以获得Python样式划分

from __future__ import division

作为每个源文件中的第一行源代码。

其他回答

与许多类c语言一样,它是余数运算或模运算。有关数字类型(int, float, long, complex)请参阅文档。

X % y计算除法X除以y的余数,其中商为整数。余数是y的符号。


在Python 3上,计算结果为6.75;这是因为/做的是真除法,而不是像Python 2中那样(默认情况下)的整数除法。在Python 2上,1 / 4给出0,因为结果是四舍五入。

整数除法也可以在python3上执行,使用//操作符,因此要得到7,你可以执行:

3 + 2 + 1 - 5 + 4 % 2 - 1 // 4 + 6

此外,在python2中,只需添加该行,就可以获得Python样式划分

from __future__ import division

作为每个源文件中的第一行源代码。

这是一个模运算 http://en.wikipedia.org/wiki/Modulo_operation

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

根据运算的顺序,结果是

(3+2+1-5) + (4%) 2 - (1/4) + 6

(1) + (0) - (0) + 6

7

1/4=0,因为我们在做整数运算。

在大多数语言中%表示模数。Python也不例外。

模运算符,通常用于整数的余数除法,但在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].