完美的方形功能,不会返回

时间:2016-10-17 15:00:54

标签: python loops if-statement

我是初学者,正在使用Python,我得到了这个任务:编写一个返回最大完美正方形的函数,该正方形小于或等于其参数(正整数)。 < / p>

def perfsq(n):

    x = 0
    xy = x * x
    if n >= 0:
        while xy < n:
            x += 1

        if xy != n:
            print (("%s is not a perfect square.") % (n))
            x -= 1
            print (("%s is the next highest perfect square.") % (xy))
        else:
            return(print(("%s is a perfect square of %s.") % (n, x)))

当我运行代码来执行该功能时,它不会输出任何内容。我承认,我很挣扎,如果你能就如何解决这个问题给我一些建议,我将不胜感激。

4 个答案:

答案 0 :(得分:1)

您的循环条件

while xy < n:

这将是真的,因为xy始终为0,如果你将n = 0调用函数,则n总是大于零,它将打印0 is a perfect square of 0.并返回None。

for n > 0

为什么在true的情况下始终为xy < n,因为您已分配xy 0并且在循环运行时从未将其修改为任何其他值,请检查条件并始终得到True

答案 1 :(得分:0)

就像Patrick Haugh所说,尝试检查while循环何时退出。在整个方法中放置print()语句以确定方法的执行方式会很有帮助。为了弄清楚循环何时退出,请查看while循环的退出条件:xy&lt; ñ。

请记住,在您更新变量之前,变量不会更新。

def perfsq(n):
    x = 0
    xy = x * x
    print("xy: {}".format(xy))
    if n >= 0:
        while xy < n:
            x += 1
            print("xy in loop: {}".format(xy))

        if xy != n:
            print (("%s is not a perfect square.") % (n))
            x -= 1
            print (("%s is the next highest perfect square.") % (xy))
        else:
            return(print(("%s is a perfect square of %s.") % (n, x)))

答案 2 :(得分:-1)

我看到了你的错误,这对某人来说很容易。定义时

xy = x*x

计算机计算x*x并将数字指定为xy的值。因此,当您向x添加一个时,它不会更改xy的值。您必须告诉计算机每次重新计算xy

while xy < n:
    x += 1
    xy = x*x

答案 3 :(得分:-1)

main {background-color: blue;}

想一想。

相关问题