1. 程式人生 > >關於python3 四捨五入round()函式的坑,給出調整的邏輯

關於python3 四捨五入round()函式的坑,給出調整的邏輯

# 關於python3四捨五入函式的處理,示例:3.5 2.5 
# 由於整數部分為偶數,並且小數部分只有0.5的情況下
# round()函式會近似到偶數部分(見原doc解釋)
# 需要+1處理, 其餘情況round()函式輸出正常
# “values are rounded to the closest multiple of 10 to 
# the power minus ndigits; if two multiples are equally 
# close, rounding is done toward the even choice.” 
# 如果距離兩邊一樣遠,會保留到偶數的一邊
# 涉及浮點數儲存精度不同,0.5儲存約為0.499999···
n = float(input())
if int(n)%2 == 0 and n-int(n)==0.5 :
    print(int(n)+1)
else:
    print(round(n))