【问题标题】:Python - Wildcards for integer values?Python - 整数值的通配符?
【发布时间】:2020-02-10 20:57:16
【问题描述】:

如何让我的代码对任何小数点为 x.999999999 的值进行四舍五入?

到目前为止我的代码是:

y = int(input("Enter a cube number "))
cuberoot = y**(1/3)
if cuberoot.is_integer():
    print("integer")
else:
    if cuberoot == HERE.9999999:
        print("Integer")
    else:
        print("not integer")

帮助 (它说“这里”是我放在那里的)

【问题讨论】:

    标签: python python-3.x rounding wildcard


    【解决方案1】:

    使用模运算符。

    y = int(input("Enter a cube number "))
    cuberoot = y ** (1/3)
    fraction = cuberoot % 1
    if fraction == 0 or fraction > 0.999999:
        print("integer")
    else:
        print("not integer")
    

    【讨论】:

    • 这很好用,现在我如何将问题设置为已回答
    • 作为参考,这个失败的最小数字是 193,100,551,它不是一个立方体(它是 578^3 - 1)。
    【解决方案2】:

    使用容错会为您提供较大数字的错误结果。例如,1012 - 1 不是立方体,但 (10**12 - 1) ** (1/3)9999.999999996662,它会通过您的测试。

    更安全的方法是将其四舍五入为整数,然后检查它是否具有正确的立方体:

    def is_cube(x):
        y = x ** (1/3)
        y = int(round(y))
        if y ** 3 == x:
            print('Integer')
        else:
            print('Not integer')
    

    例子:

    >>> is_cube(27)
    Integer
    >>> is_cube(28)
    Not integer
    >>> is_cube(10**12)
    Integer
    >>> is_cube(10**12 - 1)
    Not integer
    

    但是,请注意,这不适用于 非常 大的数字,因为 x ** (1/3) 是使用浮点数完成的,因此误差可能大于 0.5,在这种情况下会四舍五入会给出错误的结果。例如,对于输入10 ** 45,上述代码失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多