我正在做一个小任务。任务是对货币分配器计算器进行编程。基本版本可能会产生以下输出:
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=348
,number_of_notes=3
,这对于amount
中的$ 100条记的数量是正确的,residual=174
1}}。
我只是想让我的find_denom
功能先行,但我不确定从哪里开始。
答案 0 :(得分: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)
答案 1 :(得分: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