我使用Euclidean algorithm来寻找两个数的最大公约数,使用递归。在
我很困惑,因为在某个时刻b的值将等于0,此时我已经指定程序返回a的值,此时这个值应该是最大的公约数。在
程序不会这样做。相反,我被告知我需要在else步骤中将return放在gcdRecur之前。但是为什么这是必要的,因为一旦b==0,程序就应该退出if语句?在
def gcdRecur(a, b):
if b == 0:
return a
else:
gcdRecur(b, a%b)
gcdRecur(60,100)
Tags:
您需要实际返回递归调用的值:
您忽略了调用的递归值:
在此处添加
^{pr2}$return
:递归调用返回值不是自动传递的;它就像任何其他函数调用一样,如果希望返回结果,则需要显式地传递。在
演示:
相关问题 更多 >
编程相关推荐