这是我发现的最好的方法:
x = int(raw_input("Enter an integer: "))
for ans in range(0, abs(x) + 1):
if ans ** 3 == abs(x):
break
if ans ** 3 != abs(x):
print x, 'is not a perfect cube!'
else:
if x < 0:
ans = -ans
print 'Cube root of ' + str(x) + ' is ' + str(ans)
是否有更好的方法,最好是避免迭代候选值的方法?
你可以使用x ** (1. / 3)
计算(浮点)立方根x
.
这里的细微之处在于,在 Python 2 和 3 中,这对于负数的工作方式有所不同。但是,以下代码可以处理该问题:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
这取立方根x
,四舍五入到最接近的整数,并取三次方,最后检查结果是否等于x
.
取绝对值的原因是为了使代码能够在不同 Python 版本中正确处理负数(Python 2 和 3 对负数的分数幂的处理方式有所不同)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)