Python常用函数round()、floor()、ceil()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Elvirangel/article/details/83500861

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、

Python 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

Python3 ceil() 函数

Python3 数字 Python3 数字


描述

ceil(x) 函数返回一个大于或等于 x 的的最小整数。


语法

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

import math

math.ceil( x )

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


参数

x -- 数值表达式。


返回值

函数返回返回一个大于或等于 x 的的最小整数。


实例

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

#!/usr/bin/python3
import math   # 导入 math 模块

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(math.pi) : ", math.ceil(math.pi))

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

math.ceil(-45.17) :  -45
math.ceil(100.12) :  101
math.ceil(100.72) :  101
math.ceil(math.pi) :  4

猜你喜欢

转载自blog.csdn.net/Elvirangel/article/details/83500861
今日推荐