纸币和硬币在计算器中工作,但不在程序上



我试图将其发送到URI,但错误了10%。对于输入 576.43,它最终给出 2 美分。我在计算器中完全按照我的代码进行了所有数学运算,最后得到了 3 美分。怎么了?

total = float(input())
bill100 = int((total) / 100)
total = ((total) - (bill100*100))
bill50 = int((total)/50)
total = (total - (bill50*50))
bill20 = int(total/20)
total = (total - (bill20*20))
bill10 = int(total/10)
total = (total - (bill10*10))
bill5 = int(total/5)
total = (total - (bill5*5))
bill2 = int(total/2)
total = (total - (bill2*2))
coin1dolar = int(total)
total = (total - coin1dolar)
coin50 = int(total/0.50)
total = (total - (coin50*0.50))
coin25 = int(total/0.25)
total = (total - (coin25*0.25))
coin10 = int(total/0.10)
total = (total - (coin10*0.10))
coin5 = int(total/0.05)
total = (total - (coin5*0.05))
coin1cent = int(total/0.01)
print("BILLS:")
print(str(bill100) + " bills of R$ 100.00")
print(str(bill50) + " bills of R$ 50.00")
print(str(bill20) + " bills of R$ 20.00")
print(str(bill10) + " bills of R$ 10.00")
print(str(bill5) + " bills of R$ 5.00")
print(str(bill2) + " bills of R$ 2.00")
print("COINS:")
print(str(coin1dolar) + " coins of R$ 1.00")
print(str(coin50) + " coins of R$ 0.50")
print(str(coin25) + " coins of R$ 0.25")
print(str(coin10) + " coins of R$ 0.10")
print(str(coin5) + " coins of R$ 0.05")
print(str(coin1cent) + " coins of R$ 0.01")

你的问题是浮点数学不精确。您可以在python文档中阅读有关它的信息。您不断使用浮点值进行除法。您可以通过执行coin1cent = int(round(total/.01))来解决此问题。

另外,我认为您还应该查看此处链接的mod运算符。

最新更新