简体   繁体   English

Python 2 is_integer无法正确返回

[英]Python 2 is_integer not returning properly

from fractions import Fraction

counter = 0;
a = int(raw_input())
b = int(raw_input())

if 1 <= a <= 10 ** 8:
    if a <= b <= 10 ** 8:
        for i in range(a, b+1):
            if float(i**Fraction(1,3)).is_integer() == True:
                counter += 1
                print(i)

print(str(counter))
print (str(float(64**Fraction(1,3)).is_integer()))

This code returns false which results in the if statement not being run at all. 此代码返回false,这将导致if语句根本不运行。 Furthermore, the cube root of 64 is 4, therefore, the result should be an integer. 此外,立方根64为4,因此,结果应为整数。 However, in the range between 1 and 100 inclusive, 1, 8, and 27 return true for this case. 但是,在1到100(含1和100)之间的范围内,在这种情况下,1、8和27返回true。 Any help would be appreciated as to why the cube root of 64 is not returning true. 对于为什么64的立方根未返回true的任何帮助,我们将不胜感激。

You have used float for the cube root value. 您已将float用于多维数据集根值。 The following code gives you the value of float(i**Fraction(1,3)) = 3.9999999 以下代码为您提供了float(i**Fraction(1,3)) = 3.9999999

Try rounding the value first before converting it to float. 尝试先舍入该值,然后再将其转换为浮点型。

if float(round(i**Fraction(1,3),2)).is_integer() == True:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM