在Python中用便士计算?

我正在
python中进行更改程序.用户必须输入一个美元金额,然后程序将计算二十,十,五,一,四分之一,硬币,镍币和便士的变化.我被指示使用圆形功能来赚钱,因为如果我输入58.79美元的金额,程序会告诉我当它应该是4时给3便士.有没有办法把这些便士弄圆?

我知道一分钱的价值是.01,但是python将其读作.100000000001我认为是问题所在.

任何帮助表示赞赏,这里是我需要舍入的部分:

# get the amount to change from the user

change = input("Please enter the amount to change: $")

print "To make change for $",change,"give the customer back:"

# calculate number of twenties
twenties = int(change/ 20)

print twenties, "twenties"

change = change - twenties *20

# calculate tens
tens = int(change / 10)

print tens, "tens"

change = change - tens *10

#calculate fives
fives = int(change / 5)

print fives, "fives"

change = change - fives *5

#calculate ones
ones = int(change / 1)

print ones, "ones"

change = change - ones * 1

#calculate quarters
quarters = int(change / .25)

print quarters, "quarters"

change = change - quarters * .25

#calculate dimes
dimes = int(change / .10)

print dimes, "dimes"

change = change - dimes * .10

#calculate nickels
nickels = int(change / .05)

print nickels, "nickels"

change = change - nickels * .05

#calculate pennies
pennies = int(change / .01)

print pennies, "pennies"

最佳答案 您遇到的问题是浮点运算不精确的结果.在IEEE浮点中无法精确表示0.01.这是使用货币时不使用浮动的一个原因.

您应该使用小数甚至整数,因为您知道小数点后最多有2位数.在这种情况下,只需要用便士的数量.

关于问题本身,我认为最简单的方法是将美元金额转换为便士金额,然后迭代预定义的值列表,其中包含每种面额的等量硬币(按降序排列):

def change(amount):

    # this can be removed if you pass the amount in pennies
    # rather than dollars
    amount = int(round(amount*100))

    values = [2000, 1000, 500, 100, 25, 10, 5, 1]
    denom = ['twenties', 'tens', 'fives', 'ones', 'quarters', 'dimes', 'nickels', 'pennies']

    for i in range(len(values)):
        num = amount / values[i]
        amount -= num * values[i]
        print str(num) + " " + denom[i]

现在调用更改(58.79)将打印

2 twenties
1 tens
1 fives
3 ones
3 quarters
0 dimes
0 nickels
4 pennies

正如codepad.org所见

点赞