首先,amountLeft/0.02 >= 1
大部分與amountLeft >= 0.02
(假設amountLeft
不是負數)相同,並且有點簡單。
使用整數運算(與便士工作直接,會給你確切的結果,但你必須手動添加.
顯示結果時:
from Decimal import decimal
amountLeft = round(amountLeft*100)
....
elif amountLeft >= 2:
changeGiven.append("2p")
amountLeft -= 2
else:
changeGiven.append("1p")
amountLeft -= 1
如果你真的需要一個程序來處理在小數具體的方式,使用十進制模塊假設輸入是浮點:
# Assume amountLeft contains a floating point number (e.g. 1.99)
# 2 is the number of decimals you need, the more, the slower. Should be
# at most 15, which is the machine precision of Python floating point.
amountLeft = round(Decimal(amountLeft),2)
....
# Quotes are important; else, you'll preserve the same errors
# produced by the floating point representation.
elif amountLeft >= Decimal("0.02"):
changeGiven.append("2p")
amountLeft -= Decimal("0.02")
else:
changeGiven.append("1p")
amountLeft -= Decimal("0.01")
如果您願意投入一些時間和精力得到什麼是怎麼回事有了更深的瞭解,我建議你閱讀[什麼每一臺計算機科學家應該瞭解浮點運算](http://docs.oracle.com。com/cd/E19957-01/806-3568/ncg_goldberg.html) –