Python中的模运算符 [英] Modulo operator in Python
问题描述
以下代码中的模是做什么的?
What does modulo in the following piece of code do?
from math import *
3.14 % 2 * pi
我们如何计算浮点数的模数?
How do we calculate modulo on a floating point number?
推荐答案
当您具有表达式时:
a % b = c
这实际上意味着存在一个整数n
,该整数会使c
尽可能小,但不可为负.
It really means there exists an integer n
that makes c
as small as possible, but non-negative.
a - n*b = c
用手,您可以一遍又一遍地减去2
(如果您的数字为负数,则可以加2
),直到最终结果是可能的最小正数:
By hand, you can just subtract 2
(or add 2
if your number is negative) over and over until the end result is the smallest positive number possible:
3.14 % 2
= 3.14 - 1 * 2
= 1.14
此外,3.14 % 2 * pi
被解释为(3.14 % 2) * pi
.我不确定您是否要编写3.14 % (2 * pi)
(在任何一种情况下,算法都是相同的.只需加/减,直到数字尽可能小为止).
Also, 3.14 % 2 * pi
is interpreted as (3.14 % 2) * pi
. I'm not sure if you meant to write 3.14 % (2 * pi)
(in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).
这篇关于Python中的模运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!