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.
相关文章