[英]What is wrong with my simple python code?
I need to create a script that asks the user for a $ amount and then outputs the minimum amount of coins to create that $ amount using quarters, dimes, nickels, and pennies. 我需要创建一个脚本,要求用户提供$金额,然后输出最小数量的硬币,以使用四分之一,一角硬币,镍币和几美分硬币来创建该$金额。
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)
For some reason it only works if I enter 0.01, 0.05, 0.10 or an exact multiple of 0.25, otherwise the while loop goes on forever. 由于某些原因,它仅在我输入0.01、0.05、0.10或0.25的精确倍数时有效,否则while循环将永远继续下去。
Thanks guys! 多谢你们! I managed to fix it by multiplying the input by 100 and turning it into an integer. 我设法通过将输入乘以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)
You can do: round((float(input("Enter the amount you are owed in $:")))) 您可以执行以下操作:round((float(input(“输入您在$中的欠款:”)))))
The problem is that when you cast to a float, the string to float conversion will not be 100% accurate. 问题是,当您强制转换为浮点数时,字符串到浮点数的转换将不会100%准确。 For example if you were to type in 1.17 and cast that to a float, it would be be something like 1.1699999999999999. 例如,如果您输入1.17并将其转换为浮点数,则将类似于1.1699999999999999。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.