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() 有什么区别?
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
