代码之家  ›  专栏  ›  技术社区  ›  Kojrey

在Python中,为什么这个负浮点数会传递非负while循环测试条件?

  •  1
  • Kojrey  · 技术社区  · 1 年前
    • 使用Python
    • 收集用户输入
    • 输入必须为非负数
    • 已成功将While条件用于程序的另一部分
    • 但现在不明白为什么这个捕获有效输入的测试失败了。
    print("How many grams of xyz are required?")
    xyz_string = input()
    xyz = int(float(xyz_string))
    while xyz < 0:
         print("Sorry, the amount must be a non-negative number. Please try again.")
         print("How many grams of xyz are required")
         xyz_string = input()
         xyz = int(float(xyz_string))
    all_xyz.append(xyz)
    

    测试时,我输入了:

    -0.8

    我原以为这不会通过非阴性测试。 但事实并非如此,无效输入退出了While循环,并附加了无效输入。

    任何帮助都将不胜感激。

    2 回复  |  直到 1 年前
        1
  •  1
  •   Anerdw    1 年前

    问题在于表达 int(float(xyz_string)) .这将使你的所有数字四舍五入 towards zero ,因此,如果您输入的数字在0到-1之间,它将四舍五入为零并通过测试。

    要解决这个问题,只需延迟您的 int 调用直到您完成输入:

    print("How many grams of xyz are required?")
    xyz_string = input()
    xyz = float(xyz_string)
    while xyz < 0:
         print("Sorry, the amount must be a non-negative number. Please try again.")
         print("How many grams of xyz are required")
         xyz_string = input()
         xyz = float(xyz_string)
    all_xyz.append(int(xyz))
    
        2
  •  -2
  •   Thierry Lathuille    1 年前

    我并不确切知道你的代码中有什么问题,它既混乱又复杂,所以最好的办法就是这样简化它-

    carbs_str = "How many grams of carbohydrates are required?"
    carbs = float(input(carbs_str))
    while carbs < 0:
          print("Sorry, the amount must be a non-negative number. 
          Please try again.")
          carbs = float(input(carbs_str))