我正在研究下面的问题,第二部分。然而,当我在python中实现它时,它失败了,“RecursionError:maximum recursion depth exceeded”。
这是我的算法:
import math
def sumofpowers2(x):
count = 1
if math.isclose(x ** count,0,rel_tol=0.001):
return 0
count += 1
return 1 + x * sumofpowers2(x)
print(sumofpowers2(0.8))
已编辑。你知道吗
首先,请学习基本调试:在依赖值之前添加一个简单的
print
来跟踪值:输出:
这就指出了关键问题:每次进入例程时,都将
count
重置为1。简单的解决方法是将初始化提升到循环之外:输出:
更好的是,将
count
作为一个添加到函数中的参数:并不是说你的级联算法不是你期望的值。你知道吗
简而言之,
sumofpowers2(x)
使用相同的参数调用自身,导致无限递归(除非if
条件从一开始就是真的,否则它永远不会是真的)。你知道吗每次
sumofpowers2()
调用自身时,都会创建一个名为count
的新变量并将其设置为1
。要使这段代码正常工作,您需要找出一种方法来跨调用携带count
的值。你知道吗相关问题 更多 >
编程相关推荐