【问题标题】:What is wrong with my simple python code?我的简单 python 代码有什么问题?
【发布时间】:2018-09-27 11:09:11
【问题描述】:

我需要创建一个脚本,要求用户输入 $ 金额,然后输出最小数量的硬币以使用硬币、硬币、镍和便士创建该 $ 金额。

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 循环将永远持续下去。

【问题讨论】:

  • 你试过了吗-while(mTotal > 0):
  • 这是你应该做的。在while loop开头,加上print(mTotal),运行程序看看为什么不停止
  • 我在 while 循环的开头添加了 print(mTotal),它一直在打印一个非常小的数字。像 5.03e-17 这样的东西。为什么会这样??
  • 您不应该使用浮点值来赚钱。你应该使用整数美分。
  • 请阅读stackoverflow.com/questions/19473770/…获取解释和解决方案。

标签: python


【解决方案1】:

你可以这样做: round((float(input("请输入您的欠款金额:$:"))))

问题在于,当您转换为浮点数时,字符串到浮点数的转换不会 100% 准确。例如,如果您要输入 1.17 并将其转换为浮点数,那么它将类似于 1.1699999999999999。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多