我有这个python代码:
def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square.'
return None
else:
print x, ' is a perfect square.'
return ans
else:
print x, ' is not a positive number.'
return None
y = 16
sqrt(y)
输出为:
16 is not a perfect square.
鉴于这一点非常有效:
x = 16
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
#print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans, 'is a perfect square'
else: print x, 'is not a positive number'
我做错什么了?
我想我可以提供一个更简单的解决方案:
这对
n < 2**52 + 2**27 = 4503599761588224
有效。示例:
正确缩进代码,让
while
语句执行到ans*ans < x
:试试看here。
您的
while
循环只执行一次。不管它内部的if
语句是哪个分支,整个函数都将立即返回。相关问题 更多 >
编程相关推荐