問題描述
在 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()
現在有什么區(qū)別?
So what is the difference, if any, between int()
and floor()
now?
推薦答案
floor()
循環(huán) down.int()
截斷.使用負數時區(qū)別很明顯:
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() 有什么區(qū)別?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!