首页 > 解决方案 > 我的简单 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 循环将永远持续下去。

标签: python

解决方案


多谢你们!我设法通过将输入乘以 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)

推荐阅读