首先,与(假设不是负数)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
如果您确实需要一个程序以精确的方式处理小数,请使用 decimal 模块。假设输入是浮点数:
# 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")