我在进行编码挑战时遇到了我从未遇到过的问题。问题要求以最有效的方式退还变更。用户输入价格,并将支付的金额作为数组(有点像向自动售货机捐款)
由于某些原因,当剩余更改为0.01时,代码不会通过最后一个if块
def ChangeMaker(price, payment):
# Write your code here
totalPayment=0
for i in payment:
totalPayment+=i
change = totalPayment-price
coinChange=change-int(change)
def helper(remain, result):
holder= result
newRemain = remain
if remain>=.25:
holder[3]+=1
newRemain-=.25
return helper(newRemain, holder)
elif remain>=.10:
holder[2]+=1
newRemain -=.10
return helper(newRemain, holder)
elif remain>=.5:
holder[1]+=1
newRemain -=.05
return helper(newRemain, holder)
elif remain>.01 or remain==.01:
holder[0]+=1
newRemain -=.01
return helper(newRemain, holder)
else:
return holder;
return helper(coinChange, [0,0,0,0])
print(ChangeMaker(1.87, [5, .25,.25,.25,.25, 1]))
答案 0 :(得分:0)
正如@gmds所说,这纯粹是一个浮点精度问题。这是一种计算货币(仅保留小数点后两位)的快速解决方案,方法是将每个数字计时100,然后将其转换为整数。
def ChangeMaker(price, payment):
# Write your code here
totalPayment=int(sum(payment) * 100)
price = int(price * 100)
change = totalPayment-price
coinChange=change % 100
def helper(remain, result):
holder= result
newRemain = remain
if remain>=25:
holder[3]+=1
newRemain-=25
return helper(newRemain, holder)
elif remain>=10:
holder[2]+=1
newRemain -= 10
return helper(newRemain, holder)
elif remain>=5:
holder[1]+=1
newRemain -= 5
return helper(newRemain, holder)
elif remain >= 1:
holder[0]+=1
newRemain -= 1
return helper(newRemain, holder)
else:
return holder
return helper(coinChange, [0,0,0,0])
print(ChangeMaker(1.87, [5, .25,.25,.25,.25, 1]))