[587]python ceil()& floor() &round()函数

ceil() 函数

描述

ceil() 函数返回数字的上入整数。

语法

以下是 ceil() 方法的语法:

import math

math.ceil( x )

注意:ceil()是不能直接访问的,需要导入 math 模块,通过静态对象调用该方法。

参数

x – 数值表达式。

返回值

函数返回数字的上入整数。

实例

以下展示了使用 ceil() 方法的实例:

#!/usr/bin/python
import math   # This will import math module

print "math.ceil(-45.17) : ", math.ceil(-45.17)
print "math.ceil(100.12) : ", math.ceil(100.12)
print "math.ceil(100.72) : ", math.ceil(100.72)
print "math.ceil(119L) : ", math.ceil(119L)
print "math.ceil(math.pi) : ", math.ceil(math.pi)

以上实例运行后输出结果为:

math.ceil(-45.17) :  -45.0
math.ceil(100.12) :  101.0
math.ceil(100.72) :  101.0
math.ceil(119L) :  119.0
math.ceil(math.pi) : 4.0

floor() 函数

描述

floor() 返回数字的下舍整数。

语法

以下是 floor() 方法的语法:

import math

math.floor( x )

注意:floor()是不能直接访问的,需要导入 math 模块,通过静态对象调用该方法。

参数

x – 数值表达式。

返回值

返回数字的下舍整数。

实例

以下展示了使用 floor() 方法的实例:

#!/usr/bin/python
import math   # This will import math module

print "math.floor(-45.17) : ", math.floor(-45.17)
print "math.floor(100.12) : ", math.floor(100.12)
print "math.floor(100.72) : ", math.floor(100.72)
print "math.floor(119L) : ", math.floor(119L)
print "math.floor(math.pi) : ", math.floor(math.pi)

以上实例运行后输出结果为:

math.floor(-45.17) :  -46.0
math.floor(100.12) :  100.0
math.floor(100.72) :  100.0
math.floor(119L) :  119.0
math.floor(math.pi) :  3.0

round()函数

描述

round() 方法返回浮点数x的四舍五入值。

语法

以下是 round() 方法的语法:

round( x [, n]  )

参数

x – 数值表达式。
n – 数值表达式。

返回值

返回浮点数x的四舍五入值。

实例

以下展示了使用 round() 方法的实例:

#!/usr/bin/python

print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)

以上实例运行后输出结果为:

round(80.23456, 2) :  80.23
round(100.000056, 3) :  100.0
round(-100.000056, 3) :  -100.0

在实际使用中发现round函数并不总是如上所说的四舍五入。如:

In  [14]: round(2.355,  2)  
Out[14]:  2.35

注:环境为 python3.5.2

因为该函数对于返回的浮点数并不是按照四舍五入的规则来计算,而会收到计算机表示精度的影响。

关于该问题搜索后解释比较清楚的文章地址如下:http://www.runoob.com/w3cnote/python-round-func-note.html

参考:http://www.runoob.com/python/func-number-ceil.html
https://www.runoob.com/python/func-number-floor.html
https://www.runoob.com/python/func-number-round.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值