Python中的模运算符 [英] Modulo operator in Python

查看:96
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆