What is the difference between int() and floor() in Python 3?(Python 3 中的 int() 和 floor() 有什么区别?)
问题描述
在 Python 2 中,floor() 返回一个浮点值.虽然对我来说不是很明显,但我找到了一些解释,阐明了为什么让
).floor()
返回浮点数可能有用(对于像 float('inf')
和 <代码>浮动('nan')
In Python 2, floor()
returned a float value. Although not obvious to me, I found a few explanations clarifying why it may be useful to have floor()
return float (for cases like float('inf')
and float('nan')
).
然而,在 Python 3 中,floor()
返回整数(并且对于前面提到的特殊情况返回溢出错误).
However, in Python 3, floor()
returns integer (and returns overflow error for the special cases mentioned before).
那么 int()
和 floor()
现在有什么区别?
So what is the difference, if any, between int()
and floor()
now?
推荐答案
floor()
循环 down.int()
截断.使用负数时区别很明显:
floor()
rounds down. int()
truncates. The difference is clear when you use negative numbers:
>>> import math
>>> math.floor(-3.5)
-4
>>> int(-3.5)
-3
对负数进行四舍五入意味着它们远离 0,截断使它们更接近 0.
Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0.
换句话说,floor()
总是会低于或等于原始值.int()
将接近于零或等于.
Putting it differently, the floor()
is always going to be lower or equal to the original. int()
is going to be closer to zero or equal.
这篇关于Python 3 中的 int() 和 floor() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 3 中的 int() 和 floor() 有什么区别?


基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01