2017-10-06 60 views
1
def height(cent): 
    height= {} 
    height["feet"]= int(cent/30.48) 
    height["inch"]= int(cent%30.48)/2.54 
    print (height) 
height (182.88) 
print (182.88/30.48) 
print (182.88%30.48) 

的輸出是: { '英寸':11,腳':6}問題與Python模

6.0

30.479999999999993

爲什麼182.88%30.48不等於零?

+1

你爲什麼期待它呢? '182.88/30.48'是6.033,而不是6。 – chepner

+1

[Similar questions/answer](https://stackoverflow.com/questions/14763722/python-modulo-on-floats) – Kyle

+0

做盡可能少的浮點運算。計算'h = int(cent/2.54)',然後用整數運算來計算'feet,inches = divmod(h,12)'。 – chepner

回答

1

因爲30.48的值真的是30.4799 ..這是因爲floating point numbers存儲在python中的方式。因此,當您將30.479999除以182.88時,得到的舍入整數爲5(即182.88 // 30.48 == 5)。所以餘下的是30.47999 ...