CS50 Pset2 Coke Machine程序while循环问题调试求助
可乐机程序故障排查与修复
需求说明
- 机器售卖50美分的可口可乐,仅接受25、10、5美分硬币
- 提示用户逐个插入硬币,每次输入后显示剩余应付款
- 当总投入金额≥50美分时,输出应找零金额;忽略非指定面额的输入
问题代码
初始代码
coins = [25,10,5] def main(): amount_due = 50 print(f"Amount Due: {amount_due}") coin = evaluated(amount_due) def evaluated(a): while True: coin = int(input("Insert Coin:").strip()) if coin != coins: print(f"Please enter your coins in the following increments: {coins}") return coin elif coin == coins: continue def amount_due(coin, amount_due): remainder = amount_due-coin if remainder <= 0: print(f"Change owed: {remainder}") if remainder > 0: print(f"Amount due: {remainder}") return remainder main()
更新后代码(修正了成员判断逻辑)
coins = [25,10,5] def main(): amount_due = 50 print(f"Amount Due: {amount_due}") coin = evaluated(amount_due) def evaluated(a): while True: coin = int(input("Insert Coin:").strip()) if coin not in coins: print(f"Please enter your coins in the following increments: {coins}") return coin elif coin in coins: continue def amount_due(coin, amount_due): remainder = amount_due-coin if remainder <= 0: print(f"Change owed: {remainder}") if remainder > 0: print(f"Amount due: {remainder}") return remainder main()
核心问题排查
evaluated函数逻辑完全错误- 遇到有效硬币时用
continue,会直接重新进入循环,不会返回有效硬币给主函数 - 遇到无效硬币时直接
return coin,导致主函数拿到无效硬币后没有后续处理 - 函数参数
a完全未使用,属于冗余参数
- 遇到有效硬币时用
main函数没有循环处理流程- 仅调用一次
evaluated,无法实现多次插入硬币的需求 - 未调用
amount_due函数来更新剩余应付款或计算找零
- 仅调用一次
amount_due函数计算逻辑错误- 找零金额应为正数,原代码会输出负数(比如投入60美分,会输出
Change owed: -10) - 没有处理剩余应付款的循环更新,无法持续接收新硬币
- 找零金额应为正数,原代码会输出负数(比如投入60美分,会输出
修复后的完整代码
coins = [25, 10, 5] def main(): amount_due = 50 print(f"Amount Due: {amount_due}") while amount_due > 0: coin = get_valid_coin() amount_due -= coin if amount_due <= 0: print(f"Change owed: {abs(amount_due)}") else: print(f"Amount Due: {amount_due}") def get_valid_coin(): while True: try: coin = int(input("Insert Coin: ").strip()) if coin in coins: return coin else: print(f"Please enter coins in denominations: {coins}") except ValueError: print("Invalid input. Please enter an integer coin value.") main()
修复说明
- 重命名
evaluated为get_valid_coin,语义更清晰,移除冗余参数 get_valid_coin循环直到获取有效硬币才返回,无效输入仅提示不返回main函数通过while循环持续处理硬币插入,直到剩余应付款≤0- 修正找零计算逻辑,用
abs(amount_due)确保输出正数 - 增加
try-except捕获非整数输入,提升鲁棒性
内容的提问来源于stack exchange,提问作者Mia
相关产品推荐
相关产品推荐

