python - 我的简单 python 代码有什么问题?
问题描述
我需要创建一个脚本,向用户询问 $ 金额,然后输出最小数量的硬币以使用硬币、硬币、镍和便士创建该 $ 金额。
mTotal = (float(input("Enter the amount you are owed in $:")))
numCoins = 0
while (mTotal != 0):
if ((mTotal - 0.25) >= 0):
mTotal-=0.25
numCoins += 1
elif ((mTotal - 0.10)>= 0):
mTotal-=0.10
numCoins += 1
elif ((mTotal - 0.05)>= 0):
mTotal-=0.05
numCoins += 1
elif ((mTotal - 0.01)>= 0):
mTotal-=0.01
numCoins += 1
print("The minimum number of coins the cashier can return is:", numCoins)
出于某种原因,它仅在我输入 0.01、0.05、0.10 或 0.25 的精确倍数时才有效,否则 while 循环将永远持续下去。
解决方案
多谢你们!我设法通过将输入乘以 100 并将其转换为整数来修复它。
userInput = (float(input("Enter the amount you are owed in $:")))
mTotal = int(userInput*100)
numCoins = 0
while (mTotal != 0):
if ((mTotal - 25) >= 0):
mTotal-=25
numCoins += 1
elif ((mTotal - 10)>= 0):
mTotal-=10
numCoins += 1
elif ((mTotal - 5)>= 0):
mTotal-=5
numCoins += 1
elif ((mTotal - 0.01)>= 0):
mTotal-=1
numCoins += 1
print("The minimum number of coins the cashier can return is:", numCoins)
推荐阅读
- uwp - 适用于 UWP 应用程序的 Google Cloud Speech API
- c# - 模型类与 DTO 的 Post Action
- tensorflow - 如何在 Mac 上安装 TensorFlow?
- mysql - 尝试将分数分配给列时接收空值
- python - Discord API 401:未经授权的错误
- scala - 适用于 Apache Spark 的 BigQuery 连接器 - 更新分区表
- r - 如何从 rvest 中的元素中刮取 id?
- spring-boot - 春季启动测试,无法加载junit测试的属性文件
- amazon-web-services - aws xray 和 golang http 调用
- three.js - 使用 Three.js 将平面几何图形放置在圆形中