寻找完美的squ

2024-03-29 07:39:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个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'

我做错什么了?


Tags: 代码nonenumberreturnifisnotsqrt
3条回答

我想我可以提供一个更简单的解决方案:

def is_square(n):
    return sqrt(n).is_integer()

这对n < 2**52 + 2**27 = 4503599761588224有效。

示例:

>>> is_square(4)
True
>>> is_square(123)
False
>>> is_square(123123123432**2)
True

正确缩进代码,让while语句执行到ans*ans < x

def sqrt(x):
    ans = 0
    if x >= 0:
        while ans*ans < x:
            ans = ans + 1

        if ans*ans != x:  # this if statement was nested inside the while
            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          
print sqrt(y)

试试看here

您的while循环只执行一次。不管它内部的if语句是哪个分支,整个函数都将立即返回。

相关问题 更多 >