解释Python cod的输出

2024-06-24 12:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,除了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

有人能解释一下到底是怎么回事吗?在

^{pr2}$

Tags: anyourischangeamount案例lessprint
3条回答

浮点数can't represent most decimal fractions exactly,就像你不能用十进制浮点表示法写出1/3的结果一样。在

使用整数改为用分计算,或使用^{} module。在

顺便说一句,这与Python无关,但与计算机通常处理浮点运算的方式有关。在

amount = 93
quarters = amount // 25
amount = amount % 25
dimes = amount // 10
amount = amount * 10
nickel = amount // 5
cents = amount % 5

//是整数除法。%是模运算符(整数除法的余数)

考虑一下,你可以传入一个列表[25,10,5,1],然后循环执行

你不能用浮点精确地表示大多数分数。我认为在你的情况下,整数是解决问题的最好办法。我重写了您的代码,使用了美分和python3。在

cents = int(input("Enter a number of cents: "))
quarter = 0
dime = 0
nickel = 0
penny = 0

while cents > 0:
    if cents >= 25:
        quarter+=1
        cents-=25
    elif cents >= 10:
        dime+=1
        cents-=10
    elif cents >= 5:
        nickel+=1
        cents-=5
    else:
        penny+=1
        cents-=1
print ("Your change is %d quarters %d dimes %d nickels %d pennies" % (quarter, dime, nickel, penny)

相关问题 更多 >