Sha*_*ars 1 python floating-point
基本上它几乎适用于除了0.93之外我尝试过的几乎所有情况.然后我在while循环中添加了"print money"以查看每次循环后它正在做什么,这就是发生的事情:
Enter an amount less than a dollar: 0.93
0.68
0.43
0.18
0.08
0.03
0.02
0.01
3.81639164715e-17
-0.01
Your change is 3 quarters 1 dimes 1 nickels 4 pennies
Run Code Online (Sandbox Code Playgroud)
有人能解释一下到底是怎么回事吗?
money = input("Enter an amount less than a dollar: ")
quarter = 0
dime = 0
nickel = 0
penny = 0
while money > 0.00:
if money >= 0.25:
quarter = quarter + 1
money = money - 0.25
elif money >= 0.10:
dime = dime+1
money = money - 0.10
elif money >= 0.05:
nickel = nickel + 1
money = money - 0.05
else:
penny = penny + 1
money = money - 0.01
print "Your change is %d quarters %d dimes %d nickels %d pennies" % (quarter, dime, nickel, penny)
Run Code Online (Sandbox Code Playgroud)
Tim*_*ker 14
浮点数不能完全代表大多数小数部分,就像你不能使用十进制浮点表示法精确地写出1/3的结果一样.
使用整数代替美分计算,或使用decimal模块.
顺便说一下,这与Python无关,但计算机通常采用浮点数学的方式.