宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

一、向零取整:int)

python自带的int)取整

>>> int1.2)

1

>>> int2.8)

2

>>> int-0.1)

0

>>> int-5.6)

-5

总结:int)函数是“向0取整”,取整方向总是让结果比小数的绝对值更小

二、向上取整:math.ceil)

>>> import math

>>>

>>> math.ceil0.6)

1

>>> math.ceil1.1)

2

>>> math.ceil3.0)

3

>>> math.ceil-0.3)

0

>>> math.ceil-5.1)

-5

总结:math.ceil)严格遵循向上取整,所有小数都是向着数值更大的方向取整,不论正负数都如此

三、向下取整:math.floor) , “//”

>>> import math

>

>>> math.floor0.5)

0

>>> math.floor1.2)

1

>>> math.floor-0.9)

-1

>>> math.floor-3.0)

-3

>>> math.floor-3.1)

-4

总结:math.floor)严格遵循向下取整,所有小数都是向着数值更小的方向取整,不论正负数都如此

再看看python的取整“//“,同样是向下取整,记住啊:

>>> 5//3

1

>>> 1//5

0

>>> 8//4

2

>>> -6//5

-2

>>> -8//9

-1

>>> -8//2

-4

四、四舍五入 roundx,[.n])

>>> round1.1)

1

>>> round4.5)

4

>>> round4.51)

5

>>> round-1.3)

-1

>>> round-4.5)

-4

>>> round-4.51)

-5

>>> round1.248,2)

1.25

>>> round1.241,2)

1.24

>>> round-1.248,1)

-1.2

>>> round1.25,1)

1.2

>>>

这里注意:round4.5)的结果是4,round4.51)的结果才是5,这里要看5后面的数字,只有大于5时才进1,恰好等于5时还是舍去的。这与我们字面上理解的”五入“有所出入Python 3.7.4)。

五、分别取整数和小数部分 math.modf)

>>> math.modf100.123)

0.12300000000000466, 100.0)

>>> math.modf-100.123)

-0.12300000000000466, -100.0)

>>>

math.modf)函数得到一个x,y)的元组,x为小数部分,y为整数部分这里xy均为float浮点数)

注意:结果是”小数+整数“,而非”整数+小数“。

六、%求模

python运算符%取模 – 返回除法的余数

>>> 5%2

1

>>> 0.5%2

0.5

>>> 5.3%2

1.2999999999999998“`

正数很好理解,这里返回的余数时一个无线接近结果的近似值。

“`python

>>> -2.5%8

5.5

>>> -3.2%2

0.7999999999999998

>>> 5%-2

-1

>>> 5%-3)

-1

>>> 5.2%-2

-0.7999999999999998

>>> -8%-3

-2

>>> -2%-8

-2

>>> -2%-9

-2

懵了,为什么不是:-2.5和-1.2,而是:5.5和0.8?

求模运算规则是由除法规则定的:

模=被除数-除数×商

这里的”商”的值其本质是由python的整除//采取的向下取整算法决定的。所以,整理下公式就是这样的:

模=被除数-除数×被除数//除数)