[英]What is wrong with my simple python code?
我需要创建一个脚本,要求用户提供$金额,然后输出最小数量的硬币,以使用四分之一,一角硬币,镍币和几美分硬币来创建该$金额。
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)
您可以执行以下操作:round((float(input(“输入您在$中的欠款:”)))))
问题是,当您强制转换为浮点数时,字符串到浮点数的转换将不会100%准确。 例如,如果您输入1.17并将其转换为浮点数,则将类似于1.1699999999999999。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.