You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何改进ATM存款算法,正确输出所有面额纸币数量

修复ATM存款面额计算算法

原代码存在两个核心问题:

  • 使用elif分支,程序只会执行第一个满足条件的分支,剩余金额对应的面额直接被跳过,导致19仅输出Tens、55仅输出Fifties。
  • 计算各面额数量时未扣除已分配的金额,逻辑错误(比如55直接用55//50得到1,但剩余5元未处理)。

修正后的代码如下:

money = int(input("Enter amount between 1 and 200: "))

if money > 200 or money < 1:
    print("Invalid amount. Enter a number between 1 and 200.")
else:
    remaining = money
    # 从高到低计算各面额数量,同时更新剩余金额
    hundreds = remaining // 100
    remaining %= 100
    
    fifties = remaining // 50
    remaining %= 50
    
    twenties = remaining // 20
    remaining %= 20
    
    tens = remaining // 10
    remaining %= 10
    
    fives = remaining // 5
    remaining %= 5
    
    ones = remaining
    
    print(f"You have deposited {money} dollar bill(s).")
    # 仅输出数量大于0的面额
    if hundreds > 0:
        print(f"Hundreds: {hundreds}")
    if fifties > 0:
        print(f"Fifties: {fifties}")
    if twenties > 0:
        print(f"Twenties: {twenties}")
    if tens > 0:
        print(f"Tens: {tens}")
    if fives > 0:
        print(f"Fives: {fives}")
    if ones > 0:
        print(f"Ones: {ones}")

修正逻辑说明:

  1. 剩余金额跟踪:用remaining变量记录扣除当前面额后的剩余金额,每计算完一个面额就通过取余更新remaining,确保下一面额只计算剩余的钱。
  2. 独立判断输出:改用多个独立的if判断,只要该面额数量大于0就输出,保证所有符合条件的面额都会被打印。

测试输出示例:

输入19时:

Enter amount between 1 and 200: 19
You have deposited 19 dollar bill(s).
Tens: 1
Fives: 1
Ones: 4

输入55时:

Enter amount between 1 and 200: 55
You have deposited 55 dollar bill(s).
Fifties: 1
Fives: 1

内容的提问来源于stack exchange,提问作者Mono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 10:03:24