【问题标题】:checking for decimal points using a while loop使用 while 循环检查小数点
【发布时间】:2018-12-04 02:32:08
【问题描述】:

我写了一些代码来检查两个输入变量是否包含小数点:

while "." in n:
    print()
    print("Please enter only integer numbers")
    n = input("Please enter the numerator:")
    d = input("Please enter the denominator:")

while "." in d:
    print()
    print("Please enter only integer numbers")
    n = input("Please enter the numerator:")
    d = input("Please enter the denominator:")

但是,如果小数点后跟 0,我需要一种方法来忽略这些循环,例如4.0 或 8.0。

有没有办法做到这一点,或者有更好的方法来检查输入的数字是否为小数?我不想从一开始就将输入设为浮点数,因为如果用户输入整数,它也需要工作。

我使用的python版本是3.5.4。

【问题讨论】:

  • while "." in n and ".0" not in n: ?

标签: python python-3.x while-loop


【解决方案1】:

这是您正在寻找的解决方案

while int(float(d)) != float(d) or int(float(n)) != float(n):

其他答案不适用于8.05等数字

【讨论】:

  • 你是对的,但是,我似乎无法让它工作,不断收到这个错误:ValueError: invalid literal for int() with base 10: '8.4'。任何想法我做错了什么?
  • 这是因为您不能将“浮点字符串”作为 int 函数的输入。我编辑了代码,它现在应该可以工作了@YasminPaksoy
【解决方案2】:

背负@public static void main 的答案, 你也可以巩固你的循环。

while ("." in n and ".0" not in n) or ("." in d and ".0" not in d):
    n = input("Enter the numerator: ")
    d = input("Enter the denominator: ")

【讨论】:

  • "8.005" 呢?
【解决方案3】:

替换这个:

while "." in n:

用这个:

while "." in n and ".0" not in n:

这使得循环中的代码在“.”时执行。在n 中找到,但在n 中找不到“.0”

【讨论】:

    【解决方案4】:

    考虑将它们作为实际值类型进行比较:

    while int(float(d)) != float(d) or int(float(n)) != float(n):

    【讨论】:

    • 你应该尝试提供一个更有建设性和原始的答案,这个看起来和已经发布的非常相似
    • 这是真的,但是在编写另一个答案中的代码时,我无法在此处发表评论。
    • 编辑答案也被视为贡献
    • 哦,对不起!当我什至不允许发表评论时,我不知道我可以编辑答案......
    • 您可以随时建议修改,这意味着其他用户必须在修改生效之前对其进行审核。您确实需要 2k 声望才能在未经审核的情况下进行编辑。
    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 2017-04-03
    相关资源
    最近更新 更多