亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何更改此代碼以不打印未使用的硬幣=0?

如何更改此代碼以不打印未使用的硬幣=0?

一只名叫tom的貓 2023-10-11 20:03:39
我正在嘗試構建一個功能,當人們輸入金額后,它會顯示他們需要的最小硬幣或紙幣數量。但這有什么方法可以讓我改變它,這樣它就不會打印未使用的硬幣的名稱和數量嗎?(作為初學者)感謝您的幫助?。梢杂胒or循環來處理嗎?)
查看完整描述

3 回答

?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

循環可用于遍歷筆記列表,并且在循環內,如果發現有任何筆記被計數,則可以打印該筆記。


notes=[1000,500,100,50,20,10,5,2,1]


amount=int(input('Enter an amount: '))


print('Total number of notes/coins=')


for notesAmount in notes:

    if amount>=notesAmount:

       notesCount=amount//notesAmount

       amount%=notesAmount

       if notesCount>0:

          print(notesAmount, ":", notesCount)


查看完整回答
反對 回復 2023-10-11
?
慕少森

TA貢獻2019條經驗 獲得超9個贊

不要為每個面額保留一個變量,而是保留一個字典并根據所使用的面額更新 key: val 。查看代碼


amount=int(input('Enter an amount: '))


denominations = dict()


print('Total number of notes/coins=')


if amount>=1000:

    denominations['1000'] = amount//1000

    amount%=1000    

if amount>=500:

    denominations['500'] = amount//500

    amount= amount%500

if amount>=100:

    denominations['100'] = amount//100

    amount= amount%100

if amount>=50:

    denominations['50'] = amount//50

    amount= amount%50    

if amount>=20:

    denominations['20'] = amount//20

    amount= amount%20    

if amount>=10:

    denominations['10'] = amount//10

    amount= amount%10

if amount>=5:

    denominations['5'] = amount//5

    amount= amount%5   

if amount>=2:

    denominations['2'] = amount//2

    amount= amount%2    

if amount>=1:

    denominations['1'] = amount//1


for key, val in denominations.items():

    print(f"{key}: {val}")



Enter an amount: 523

Total number of notes/coins=

500: 1

20: 1

2: 1

1: 1

如果使用如下所示的簡單邏輯,則可以減少代碼行數,


def find_denominations():

    

    amount=int(input('Enter an amount: '))

    

    denominations = dict()

    

    DENOMINATIONS = [1000, 500, 100, 50, 20, 10, 5, 2, 1]

       

    print('Total number of notes/coins=')

    

    for d in DENOMINATIONS:

        if amount >= d:

            denominations[d] = amount // d

            amount %= d


    for key, val in denominations.items():

        print(f"{key}: {val}") 


查看完整回答
反對 回復 2023-10-11
?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

Sreerams 的類似實現使用 while 循環而不是 for 循環:


amount = int(input("Enter an amount: "))


counter = amount

pos = 0

notes = [1000, 500, 100, 50, 20, 10, 5, 2, 1]

output = []


while counter > 0:


    remainder = counter % notes[pos]

    sub = counter - remainder

    num = int(sub / notes[pos])

    counter -= sub

    output.append({notes[pos]: num})

    pos += 1


print("Total number of notes/coins=")


for r in output:

    for k,v in r.items():

        if v > 0:

            print("{}: {}".format(k, v))

請注意,Sreerams 代碼優于我的代碼,它更易于閱讀,并且在規模上性能更高。


查看完整回答
反對 回復 2023-10-11
  • 3 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號