2017-10-06 64 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 ...