python对一个数向上取整的实例方法
作者:silencement 时间:2023-04-12 09:07:50
python中向上取整可以用ceil函数,ceil函数是在math模块下的一个函数。
向上取整需要用到 math 模块中的 ceil() 方法:
>>> import math
>>> math.ceil(3.25)
4.0
>>> math.ceil(3.75)
4.0
>>> math.ceil(4.85)
5.0
分别取整数部分和小数部分
有时候我们可能需要分别获取整数部分和小数部分,这时可以用 math 模块中的 modf() 方法,该方法返回一个包含小数部分和整数部分的元组:
>>> import math
>>> math.modf(3.25)
(0.25, 3.0)
>>> math.modf(3.75)
(0.75, 3.0)
>>> math.modf(4.2)
(0.20000000000000018, 4.0)
知识点扩展:
python对数字的四种取整方法:int,ceil,round,modf
# int(): 向下取整3.7取3;
# math.ceil(): 向上取整3.2取4;
# round(): 四舍五入;
# math.modf(): 取整数部分和小数部分,返回一个元组:(小数部分,整数部分)。注意小数部分的结果有异议
import math
flo1 = 3.1415
flo2 = 3.500
flo3 = 3.789
print(int(flo1),math.ceil(flo1),round(flo1),math.modf(flo1))
print(int(flo2),math.ceil(flo2),round(flo2),math.modf(flo2))
print(int(flo3),math.ceil(flo3),round(flo3),math.modf(flo3))
"""
int ceil round modf
3 4 3 (0.14150000000000018, 3.0)
3 4 4 (0.5, 3.0)
3 4 4 (0.7890000000000001, 3.0)
"""
来源:https://www.py.cn/faq/python/12419.html
标签:python,向上取整
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python自动化unittest yaml使用过程解析
2023-05-06 11:48:15
![](https://img.aspxhome.com/file/2023/8/75358_0s.png)
jquery判断元素是否隐藏的多种方法
2024-04-19 10:23:51
python判断给定的字符串是否是有效日期的方法
2023-04-07 20:07:07
科讯CMS编辑器会自动更改代码
2008-12-12 13:00:00
![](https://img.aspxhome.com/file/UploadPic/200812/12/kesion-editer-90s.jpg)
js判断运行jsp页面的浏览器类型以及版本示例
2024-05-13 10:36:10
django+mysql的使用示例
2022-10-24 20:34:15
![](https://img.aspxhome.com/file/2023/9/67259_0s.png)
js 中以 ... 为前缀的几种用法详解
2024-04-18 09:40:38
![](https://img.aspxhome.com/file/2023/9/136359_0s.png)
asp中的on error resume next用法
2008-03-09 15:22:00
Python实现Kerberos用户的增删改查操作
2023-07-29 09:39:52
![](https://img.aspxhome.com/file/2023/3/61483_0s.jpg)
MySQL中SQL模式的特点总结
2024-01-13 16:08:05
python读取各种文件数据方法解析
2021-08-31 09:16:54
![](https://img.aspxhome.com/file/2023/7/121527_0s.jpg)
php tpl模板引擎定义与使用示例
2023-11-14 22:04:49
Pyqt5 实现窗口缩放,控件在窗口内自动伸缩的操作
2022-10-16 06:32:09
![](https://img.aspxhome.com/file/2023/7/91997_0s.jpg)
Mysql字符集和排序规则详解
2024-01-17 05:27:46
python用reduce和map把字符串转为数字的方法
2023-05-06 08:23:42
教你快速上手Selenium爬虫,万物皆可爬
2022-01-02 18:44:31
![](https://img.aspxhome.com/file/2023/0/105570_0s.png)
阿里云ECS服务器部署django的方法
2023-04-09 10:00:26
vue递归获取父元素的元素实例
2024-05-05 09:24:34
如何做一个只搜索本网站的引擎?
2010-07-12 19:02:00
Python 实现进度条的六种方式
2022-09-26 02:22:08
![](https://img.aspxhome.com/file/2023/6/131006_0s.gif)