python - 寻找数字的变化
问题描述
我是初学者,我得到了一个项目。我现在写下的内容适用于除我需要 83 之外的每个数字,它说我不需要镍。我尝试进行不同的操作,但这会使数学与其他数字混淆。如果你能帮忙那就太好了。
total = int(input("Enter change [0...99]: "))
half = total // 50
quarter = total % 50 // 25
dimes = total % 25 // 10
nickels = total % 10 // 5
pennies = total % 5 // 1
print(half, "half (ves)")
print(quarter, "Quarter (s)")
print(dimes, "Dime (s)")
print(nickels, "Nickel (s)")
print(pennies, "penny (s)")
解决方案
您应该total
在每枚硬币后更新:
half = total // 50
total = total % 50
# ...
这是因为并非所有代币都是前面所有代币的分隔符。例如25
,从一个数量中移除会改变它的可分性10
,因此total % 10
与remainder_after_dimes
(如果您有奇数个季度)的数量不同。
这可以在一个步骤中完成,使用divmod
:
half, total = divmod(total, 50)
quarter, total = divmod(total, 25)
dimes, total = divmod(total, 10)
nickels, total = divmod(total, 5)
pennies, total = divmod(total, 1)
推荐阅读
- c++ - 编程中“重载”一词的真正含义
- console - 什么是 C++/WinRT 中的绝对路径
- sql - 如何从oracle sql中给出的月份和年份创建日期列?
- api - 为 GraphQL 突变建模
- javascript - 如何使用 isRequired 道具和 onclick 测试渲染或不渲染的子组件
- salesforce - 请指导我如何在 LWC 中调用方法
- json - 提高 JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1, (char 0), Pushshift
- reactjs - 无法使用 React Hooks 转换 null 或 undefined
- c# - 如何使用 roslyn 在 C# 中生成/编辑打字稿代码
- php - 更新恢复ID帖子的ACF字段表单字段