详解Python3中ceil()函数用法

yipeiwu_com5年前Python基础

描述

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

python 向上取整ceil 向下取整floor 四舍五入round

#encoding:utf-8
import math

#向上取整
print "math.ceil---"
print "math.ceil(2.3) => ", math.ceil(2.3)
print "math.ceil(2.6) => ", math.ceil(2.6)

#向下取整
print "\nmath.floor---"
print "math.floor(2.3) => ", math.floor(2.3)
print "math.floor(2.6) => ", math.floor(2.6)

#四舍五入
print "\nround---"
print "round(2.3) => ", round(2.3)
print "round(2.6) => ", round(2.6)

#这三个的返回结果都是浮点型
print "\n\nNOTE:every result is type of float"
print "math.ceil(2) => ", math.ceil(2)
print "math.floor(2) => ", math.floor(2)
print "round(2) => ", round(2)

运行结果:

相关文章

Python调用C语言的实现

Python中的ctypes模块可能是Python调用C方法中最简单的一种。ctypes模块提供了和C语言兼容的数据类型和函数来加载dll文件,因此在调用时不需对源文件做任何的修改。也正...

17个Python小技巧分享

1.交换变量 复制代码 代码如下: x = 6 y = 5 x, y = y, x print x >>> 5 print y >>> 6 2.if...

横向对比分析Python解析XML的四种方式

横向对比分析Python解析XML的四种方式

在最初学习PYTHON的时候,只知道有DOM和SAX两种解析方法,但是其效率都不够理想,由于需要处理的文件数量太大,这两种方式耗时太高无法接受。 在网络搜索后发现,目前应用比较广泛,且效...

Pycharm更换python解释器的方法

安装了pycharm之后有一个新装的python解释器,顶替了之前系统的python 那样的话,原来利用pip安装的一些库会无法import. 要么加入环境变量,要么更换运行的解释器:...

Python Learning 列表的更多操作及示例代码

遍历列表-for循环 列表中存储的元素可能非常多,如果想一个一个的访问列表中的元素,可能是一件十分头疼的事。那有没有什么好的办法呢?当然有!使用 for循环 假如有一个食物名单列表,通过...