c语言 - 使用递归函数调用时何时使用"return"?



我很困惑在使用递归函数调用时何时使用'return'。

我试图找到两个数字的"GCD(最大公约数("。我实际上认为可行的是:

include <stdio.h>
int gcd (int a, int b);
int main ()
{
int a, b;
printf ("Enter two numbers n");
scanf ("%d %d", &a, &b);
printf ("GCD for numbers %d and %d is %dn", a, b, gcd(a,b));
return (0);
}
int gcd (int a, int b)
{
while (a!=b)
{
if (a > b)
gcd(a-b,b);
else if (b > a)
gcd(a,b-a);
}
return (a);
}

但是上面的代码不断接受来自终端的数字,并且无法运行代码。

但是,当我按如下方式替换函数定义时,代码按预期工作,返回正确的值。

int gcd (int a, int b)
{
while (a!=b)
{
if (a > b)
return gcd(a-b,b);
else if (b > a)
return gcd(a,b-a);
}
return (a);
}

如您所见,唯一的变化是在递归函数调用之前添加"return"。考虑到在我调用 gcd(arg1, arg2( 函数的两种情况下,为什么需要返回?

考虑到在我调用 gcd(arg1, arg2( 函数的两种情况下,为什么需要返回?

出于同样的原因,任何其他调用函数并希望返回该函数调用返回的值时都需要它;因为调用它只会调用它,而不会对结果值执行任何其他操作。

我很困惑在使用递归函数调用时何时使用"return"。

每当您将return用于任何其他函数调用时,请使用return进行递归调用 - 即:何时以及因为该调用返回您希望这次返回的值。

想象一下,我们有

#include "magic.h" /* defines gcd2(), which computes GCD in some mysterious way */

然后,我们没有进行递归调用,而是将一些工作委托给它:

/* Of course this solution also works, but is not interesting
int gcd(int a, int b)
{
return gcd2(a, b);
} */
/* So, let's do something that actually shows off the recurrence relation */
int gcd(int a, int b)
{
if (a > b)
return gcd2(a-b, b);
else if (b > a)
return gcd2(a, b-a);
else
return a;
}

(我还删除了while循环,因为它与算法无关;当然,在任何情况下都会达到return,这打破了循环。

我假设我不需要复习数学理论;而且我认为为什么gcd2结果需要return很清楚。

但实际上如何委派工作并不重要;如果gcd是一个正确计算GCD的函数,并且gcd2也是这样,那么对gcd2的调用可能会被对gcd的调用所取代。这就是秘密 - 递归调用函数实际上与正常调用函数没有什么不同。只是考虑到这种可能性,需要更清楚地了解调用函数的工作原理以及它的实际作用。


当然,也可以充分利用原始while循环 - 在执行递归之前尽可能多地减去。这可能看起来像:

int gcd(int a, int b)
{
if (a > b)
while (a > b)
a -= b; /* prepare a value for the recursion. */
return gcd(a, b); /* and then recurse with that value. */
else if (b > a)
while (b > a)
b -= a; /* similarly. */
return gcd(a, b);
else /* a == b */
return a;        
}

但是,我们不妨一路走下去,转换为迭代方法:

int gcd(int a, int b)
{
while (a != b)
/* whichever is greater, adjust it downward, leaving an (a, b)
pair that has the same GCD. Eventually we reach an equal pair,
for which the result is known. */
if (a > b)
a -= b;
else
b -= a;
return a; /* since the loop exited, they are equal now. */
}

(我们也可以做模算术来一次完成多个减法;这只是一个练习。

第一个 gcd 函数"尝试"计算 gcd,但最终总是返回不变a

第二个 gcd函数以递归方式计算 gcd,每次调用返回一个 gcd。

最新更新