[英]simplest way to convert either a float or an int to the nearest integer in Python
我想定義一個函數,該函數可以接受整數或浮點數作為參數,並返回最接近的整數(即輸入參數本身已經是整數)。 我嘗試了這個:
def toNearestInt(x):
return int(x+0.5)
但不適用於負整數。
>>> toNearestInt(3)
3
>>> toNearestInt(3.0)
3
>>> toNearestInt(3.49)
3
>>> toNearestInt(3.50)
4
>>> toNearestInt(-3)
-2
我該如何解決?
Python已經為此內置了(或多或少)。
>>> round(-3, 0)
-3.0
>>> round(-3.5, 0)
-4.0
>>> round(-3.4, 0)
-3.0
>>> round(-4.5, 0)
-5.0
>>> round(4.5, 0)
5.0
當然,您可能希望將其包裝在對int
的調用中...
def toNearestInt(x):
return int(round(x, 0))
您可以在這里保留最初的方法,僅檢查輸入是否為負數,然后添加-0.5即可。
def toNearestInt(x):
a = 0.5
if x < 0:
a*=-1
return int(x+a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.