使用递归查找squre根的简单程序

sac*_*kac 0 python recursion python-3.x

嗨,我是Python的新手,我编写了一个简单的程序来查找给定数字的平方根.

n = int(input("ENTER YOUR NUMBER: "))
g = n/2
t = 0.0001

def findRoot(x):
    if ((x * x > n - t) and (x * x <= n + t)):
        return x
    else:
        x = (x + n / x) / 2
        findRoot(x)
r = findRoot(g)

print("ROOT OF {} IS {}".format(n, r))
Run Code Online (Sandbox Code Playgroud)

t 是最大错误.

我知道使用while循环很容易,但我无法弄清楚这段代码有什么问题.我调试了代码,在返回值x(第7行)后,第10行再次运行,产生"无"值.

控制台输出为任何n,n > 0(除了4)是ROOT OF (Given Number) IS None

知道如何纠正代码吗?

the*_*orm 6

你需要在else块中返回一些东西.这应该工作:

def findRoot(x):
    if ((x*x > n - t) and (x*x <= n + t)):
        return x
    else:
        x = (x + n/x)/2
        return findRoot(x)
Run Code Online (Sandbox Code Playgroud)

亚历山大在下面的评论中建议的替代方案是else完全删除,因为如果我们还没有在if块中返回,则只会到达包含在其中的代码.所以这是等价的:

def findRoot(x):
    if ((x*x > n - t) and (x*x <= n + t)):
        return x
    x = (x + n/x)/2
    return findRoot(x)
Run Code Online (Sandbox Code Playgroud)