将货币拆分为纸币的函数

2024-05-19 00:21:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须写一个函数,以“金额”作为参数。然后将“金额”作为用户输入,并将值传递给函数参数。之后,我们必须实现该功能,并计算如何将这些货币拆分为500、100、50、20、10、5、2和1塔卡纸币。 然后在函数调用中打印返回的值

如果钱是1234,那么函数应该返回:"500 Taka: 2 note(s) 100 Taka: 2 note(s) 20 Taka: 1 note(s) 10 Taka: 1 note(s) 2 Taka: 2 note(s)"

我试过:

def splitting_money(amount):
    
    five_hundred = int(amount/500)
    one_hundred = int((amount%500)/100)
    fifty = int(((amount%500)%100)/50)
    twenty = int((((amount%500)%100)%50)/20)
    ten = int(((((amount%500)%100)%50)%20)/10)
    five = int((((((amount%500)%100)%50)%20)%10)/5)
    two = int(((((((amount%500)%100)%50)%20)%10)%5)/2)
    one = int((((((((amount%500)%100)%50)%20)%10)%5)%2)/1)
    
    if amount < 500:
        print ("100 Taka: ",one_hundred,"note(s)","\n", "50 Taka: ",fifty,"note(s)","\n", "20 Taka: ",twenty,"note(s)","\n", "10 Taka: ",ten,"note(s)","\n", "5 Taka: ",five,"note(s)","\n", "2 Taka: ",two,"note(s)","\n", "1 Taka: ",one,"note(s)")
    elif amount >= 500:
        print ("500 Taka: ",five_hundred,"note(s)","\n","100 Taka: ",one_hundred,"note(s)","\n", "50 Taka: ",fifty,"note(s)","\n", "20 Taka: ",twenty,"note(s)","\n", "10 Taka: ",ten,"note(s)","\n", "5 Taka: ",five,"note(s)","\n", "2 Taka: ",two,"note(s)","\n", "1 Taka: ",one,"note(s)")  '\n' splitting_money(1234)

结果如下:

500 Taka:  2 note(s)                                                                                          
100 Taka:  2 note(s)                                                                                               
50 Taka:  0 note(s)                                                                                                  
20 Taka:  1 note(s)                                                                                                   
10 Taka:  1 note(s)                                                                                                  5 Taka:  0 note(s)                                                                                                           
2 Taka:  2 note(s)                                                                                                   
1 Taka:  0 note(s)`

这看起来不整洁。我该怎么办


Tags: 函数金额amountoneintnotefivetwo
1条回答
网友
1楼 · 发布于 2024-05-19 00:21:37

使用divmod

def to_notes(val,notes):
    remainder = val
    results = {}
    for _n in notes:
        n,remainder = divmod(remainder,_n)
        results[_n]=n
    return results

results = to_notes(1475,[500,100,50,20,10,5,1])

格式化很简单

' '.join([f'{k} taka {v} note(s)' for k,v in results.items() if v > 0])

相关问题 更多 >

    热门问题