尝试在Python中执行银行取款模拟程序时出错

2024-09-30 18:14:48 发布

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

我是Python新手,我正在尝试制作一个程序,根据用户输入从银行取款。这只适用于100美元、50美元和20美元的钞票。 如果我输入60、80、110和其他值,程序将选择可用的最高账单,而银行剩下的取款不能取款

代码如下:

 while True:
    try:
        money_amount = int(input('How much you want to withdraw? '))
        if money_amount == 0:
            print('Type in a valid value.')
            continue
    except ValueError:
        print('Not accepted. Try again.')
    else:
        print(f'Withdraw amount: $ {money_amount:.2f}')
        for bill_value in [100, 50, 20]:
            bill_quantity = money_amount // bill_value  # Divide saque // valor p/ encontrar quantia de cédulas
            money_amount %= bill_value  # Pega o resto da divisão de saque / valor. O que sobrar é calculado no próximo loop
            print(f'$ {bill_value} Bills → {bill_quantity}')

        if money_amount != 0:
            print(f'\033[31mERROR!\033[m This bank uses only \033[33m $ 100, $ 50 and $ 20 bills!!!\033[m')
            print('Try again.')
            continue
        break
print('\033[32mOperation Success\033[m')

如果我将值$1添加到项目列表中,操作将永远不会失败。。。 [100,50,20,1]-这是可行的,但这不是解决方案。。。 如果有人能帮助我理解为什么会发生这种情况以及我做错了什么,我将不胜感激


Tags: in程序ifvalue银行amountquantityvalor
1条回答
网友
1楼 · 发布于 2024-09-30 18:14:48

你的收回逻辑有一个根本性的缺陷——你从最大的去表示到最低的去表示。这不适用于您允许的有限账单

你只能换那笔钱

  • 本身除以20,不带余数
  • 或者当减去50(而不是变成负数)除以20时,没有余数
  • 100只是一种处理5个20的奇特方式

无法更改任何其他输入。您可以相应地编码:

def canBeChanged(x):
    return (x/20.0 == x//20.0) or x>=50 and ((x-50)/20.0 == (x-50)//20.0)


money = [1000, 110, 80, 60, 50, 20, 73, 10]

for m in money: 
    tmp = m
    if canBeChanged(m):
        change = []
        isDiv20 = (tmp/20.0 == tmp//20.0)  # divides by 20 without remainder
        if not isDiv20:
            change.append(50)              # remove 50, now it divides
            tmp -= 50

        twenties = tmp // 20       # how many 20's left?
        while twenties >=5:        # how many 100 bills can we combine from 5 20's?
            change.append(100)
            twenties -= 5
        while twenties:            # how many 20's left?
            change.append(20)
            twenties -= 1

        print(m, " == ", sorted(change))
    else:
        print(m, "can not be changed")

输出:

1000  ==  [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
110  ==  [20, 20, 20, 50]
80  ==  [20, 20, 20, 20]
60  ==  [20, 20, 20]
50  ==  [50]
20  ==  [20]
73 can not be changed
10 can not be changed

相关问题 更多 >