我是python的初学者,并且编写了代码检查数字是否为整数的立方。该代码对于某些值似乎运行良好,但是对于某些(甚至整个多维数据集),它会将多维数据集根打印为(x-0.000000004,即x多维数据集根)。例如,它将给出3.999999999664的立方根,但是将2,5打印为8,125。有什么想法吗?
n=int(input("Please enter the number: "))
print (n)
x=n**(1/3)
print (x)
if x==int(x):
print ('%s is a whole cube'%(n))
else:
print ('%s is not a whole cube'%(n))
Run Code Online (Sandbox Code Playgroud)
忽略中间的打印语句,它们仅用于逐行调试。
您正在检查错误的条件,比较浮点数是否相等会很容易给您带来噩梦。检查python文档对此要说些什么。
取而代之的是,将根取整,将其转换为int,然后将此整数的立方与原始数字进行比较:
n = int(input("Please enter the number: "))
print (n)
x = n**(1/3)
x = int(round(x))
if x**3 == n:
print ('%s is a whole cube'%(n))
else:
print ('%s is not a whole cube'%(n))
Run Code Online (Sandbox Code Playgroud)
正如在评论中指出的@StevenRumbalski,在Python3,x = int(round(x))可以写成round(x)以来round的回报int。