我的Python代码输出的说明

时间:2013-09-15 11:28:45

标签: 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

有人能解释一下到底发生了什么吗?

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)

3 个答案:

答案 0 :(得分:14)

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

使用整数代替美分计算,或使用decimal module

顺便提一下,这与Python无关,但计算机通常采用浮点数学的方式。

答案 1 :(得分:2)

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

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

有点想到你可以传入一个列表[25,10,5,1]并在循环中进行

答案 2 :(得分:0)

您无法使用浮点精确表达大多数分数。我认为整数是解决问题的最佳方案。我重写了你的代码以使用美分和python 3。

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)