函数返回None而不是float(仅用于某些值)

时间:2019-04-23 18:51:05

标签: python-3.x recursion

我写了一个递归二进制搜索来计算.001精度的平方根。当我的函数获得正确的值时,它不返回某些值。

def sqrtSearch(item, upper_bound, lower_bound = 0):
    midPoint = (upper_bound+lower_bound)/2
    if abs((midPoint)**2-item) <= .001:
        print(midPoint)
        return(midPoint)
    else:
        if (midPoint)**2-item > .001:
            sqrtSearch(item = item, upper_bound = midPoint, lower_bound =  lower_bound)
        else:
            sqrtSearch(item = item, upper_bound = upper_bound, lower_bound = midPoint)

x=4
rv = sqrtSearch(item=x, upper_bound = x)
print(rv)

x=9
rv = sqrtSearch(item=x, upper_bound = x)
print(rv)

我写的退货单:

2.0
2.0
3.000091552734375
None

但是“无”是意外的。为什么我可以打印此值但不返回它?

1 个答案:

答案 0 :(得分:1)

如评论中所述,您需要返回递归的结果。

def sqrtSearch(item, upper_bound, lower_bound = 0):
    midPoint = (upper_bound+lower_bound)/2
    if abs((midPoint)**2-item) <= .001:
        print(midPoint)
        return(midPoint)
    else:
        if (midPoint)**2-item > .001:
            return sqrtSearch(item = item, upper_bound = midPoint, lower_bound =  lower_bound)
        else:
            return sqrtSearch(item = item, upper_bound = upper_bound, lower_bound = midPoint)


x=4
rv = sqrtSearch(item=x, upper_bound = x)
print(rv)

x=9
rv = sqrtSearch(item=x, upper_bound = x)
print(rv)

现在给出

2.0
2.0
3.000091552734375
3.000091552734375