Python变更返回程序:计算变更时出错

时间:2019-05-30 03:12:10

标签: python

问题是当计算几分钱时,几分钱有时不足1分钱,而当计算好几分钱后,零钱最终等于.01。

import os
clear = lambda: os.system('cls')

def dollar_counter(num):

    if num // 1 >= 1:
        dollars = num // 1
    else:
        pass
    return dollars

def quarter_counter(num):

    quarters = 0
    if num // .25 >= 1:
        quarters = num // .25
    else:
        pass
    return quarters

def dime_counter(num):

    dimes = 0
    if num // .10 >= 1:
        dimes = num // .10
    else:
        pass
    return dimes 

def nickel_counter(num):

    nickels = 0
    if num // .05 >= 1:
        nickels = num // .05
    else:
        pass
    return nickels

def penny_counter(num):

    pennies = 0
    if num // .01 >= 1:
        pennies = num // .01
    else:
       pass
    return pennies

#Run Program
while True:

    try:
        #get info from user
        payment = float(input("Enter what the customer paid: "))
        cost = float(input("Enter the cost: "))

        #round change to 2 decimals and output change due
        change = round(payment - cost,2)
        print("Change due: {}".format(change))

        #count dollars
        print(int(dollar_counter(change)), "dollars")
        change = change - float(dollar_counter(change))
        print(round(change,2)) #print the change each time for troubleshooting problems

        #count quarters
        print(int(quarter_counter(change)), "quarters")
        change = change - float(quarter_counter(change)*.25)
        print(round(change,2))

        #count dimes
        print(int(dime_counter(change)), "dimes")
        change = change - float(dime_counter(change)*.1)
        print(round(change,2))

        #count nickels
        print(int(nickel_counter(change)), "nickels")
        change = change - float(nickel_counter(change)*.05)
        print(round(change,2))

        #count pennies
        print(int(penny_counter(change)), "pennies")
        change = change - float(penny_counter(change)*.01) 
        print(round(change,2))

    except UnboundLocalError:
        print("Cost can be higher than amount paid. Try again.\n")
        continue
    else:
        replay = input("Are you done? Enter 'Yes' to continue or 'No' to quit: ")
        if replay[0].lower() == 'y':
            clear()
            continue
        else:
            break

我希望几分钱之后的变化为0,但在大多数情况下,变化以== .01结尾。为什么penny_counter()不考虑剩余的变化

1 个答案:

答案 0 :(得分:0)

在dollar_counter函数中,您需要初始化dollar = 0。对于您遇到的问题,我建议在penny_counter中打印出变量num。您会看到它不完全是0.01,因此除法后将其舍入为0。要解决此问题,建议您在将结果传递给函数之前将结果舍入,或将所有单位转换为便士(因此,可以完全避免浮动)。