1

我正在做一个小任务。任务是编写一个自动提款机计算器。基本版本可能会产生以下输出:

Initial amount ($): 348
$100
$100
$100
$20
$20
$5
$2
$1

这是我的尝试:

#Pseudocode:
"""
Ask user for amount
For each demonination in [100, 50, 20, 10, 5, 2, 1]:
    Integer-divide amount by demonination
    Subtract demonination from amount to leave residual
    If residual // demonination > 1, add 1 to the count of this note, and repeat
    Otherwise go to the next denomination
"""


def find_denom(amount):
    number_of_notes = 0
    banknotes = [100, 50, 20, 10, 5, 2]
    for note in banknotes:
        residual = (amount // note)
        if residual // note > 1:
            number_of_notes += 1
    return residual, number_of_notes

amount = int(input("Enter initial amount ($): "))
residual, number_of_notes = find_denom(amount)

如果我输入 348 作为初始金额,我会得到以下变量值:amount=348number_of_notes=3,这对于 和 中的 100 美元纸币的数量是正确amountresidual=174

我只是想让我的find_denom功能首先工作,但我不确定从这里去哪里。

4

2 回答 2

1

在其他实现你想要的,使用可以使用这个功能

def find_denom(amount):
    banknotes = [100, 50, 20, 10, 5, 2, 1]
    for note in banknotes:
        counter = 0 # reassign zero to counter for every loop
        if note <= amount:
            number_of_notes = amount // note  # get the number of each note in amount
            amount = amount % note  # assign the remaining amount to amount
            while counter < number_of_notes: # check it the number of counter has exceeded the number of notes 
                print('$'+str(note)) #convert note to str and concatenate $ with it and display the note
                counter += 1

amount = int(input("Enter initial amount ($): "))
find_denom(amount)
于 2018-04-21T00:21:25.553 回答
0

您命名的变量residual不是残差,而是该音符的计数。要获得残差,请将音符乘以计数,然后从数量中减去。您也可以使用%模数运算符获得相同的数字。

您应该找到第一张小于金额的钞票,然后执行计算。

def find_denom(amount):
    banknotes = [100, 50, 20, 10, 5, 2]
    for note in banknotes:
        if note <= amount:
            number_of_notes = amount // note
            residual = amount % note
            return residual, number_of_notes
    return amount, 0
于 2018-04-20T23:52:41.357 回答