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

Python找零编程练习:计算1美元纸币数量报错如何解决?

问题原因

  • 你代码中num_ones = 19 % 5的写法是硬编码固定计算19的取模结果,仅在输入为19时输出正确,其他金额场景都会得到错误的1美元纸币数量。

正确代码

修正后的完整代码如下:

amount_to_change = int(input())

num_fives = amount_to_change // 5

''' Your solution goes here '''
num_ones = amount_to_change % 5
print('Change for $', amount_to_change)
print(num_fives, 'five dollar bill(s) and', num_ones, 'one dollar bill(s)')

逻辑说明

取模运算符%的作用是返回两个数相除的余数,amount_to_change % 5就是总找零金额除以5后剩下的不足5美元的部分,这部分刚好就是需要用1美元纸币支付的金额。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 01:51:03