使用 % 和 // 求除数

Using % and // to find divisors

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

Initial amount ($): 348
0
0
0





这是我的尝试:

#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,这对于 amount 中 100 美元纸币的数量是正确的,并且residual=174.

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

您命名的变量 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

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

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)