問(wèn)題描述
在 Python 2 中,floor()
返回一個(gè)浮點(diǎn)值.雖然對(duì)我來(lái)說(shuō)不是很明顯,但我找到了一些解釋?zhuān)U明了為什么讓 floor()
返回浮點(diǎn)數(shù)可能有用(對(duì)于像 float('inf')
和 <代碼>浮動(dòng)('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()
返回整數(shù)(并且對(duì)于前面提到的特殊情況返回溢出錯(cuò)誤).
However, in Python 3, floor()
returns integer (and returns overflow error for the special cases mentioned before).
那么 int()
和 floor()
現(xiàn)在有什么區(qū)別?
So what is the difference, if any, between int()
and floor()
now?
推薦答案
floor()
循環(huán) down.int()
截?cái)?/em>.使用負(fù)數(shù)時(shí)區(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
對(duì)負(fù)數(shù)進(jìn)行四舍五入意味著它們遠(yuǎn)離 0,截?cái)嗍顾鼈兏咏?0.
Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0.
換句話說(shuō),floor()
總是會(huì)低于或等于原始值.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.
這篇關(guān)于Python 3 中的 int() 和 floor() 有什么區(qū)別?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!