问题描述
我正在从C 编程:一种现代方法一书中学习 C 中的函数.它包含以下功能:
I'm learning about functions in C from the book C Programming: A Modern Approach. It contains the following function:
int fact(int n)
{
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
以下解释:
要了解递归是如何工作的,让我们跟踪执行语句 i = fact(3);
这里是发生了什么:
fact(3) finds that 3 is not equal or less than 1, so it calls
fact(2)which finds that 2 is not equal or less than 1, so it calls
fact(1) which finds that 1 is equal or less than 1, so it returns 1,causing
fact(2) to return 2 x 1 = 2, causing
fact(3) to return 3 x 2 = 6
我真的很困惑,如果它不在循环内,为什么它会执行所有这些操作?为什么它一直使 3 越来越少,直到它与 if 函数中的参数匹配?
I'm really confused, why does it does all these actions if it is not inside a loop? why does it keep making the 3 less and less until it matches the argument in if function?
* 符号是否表示事实 (n) 中的 n 现在是 3 - 1 并且它基本上是说它又要重新做一遍?
Does the * symbol means that n in the fact(n) is now 3 - 1 and it basically says it do it all over again?
推荐答案
递归是函数调用自身的过程.在函数定义中,您可以看到对 fact(n-1)
的调用,这意味着再次调用函数本身.
Recursion is the process when a function calls itself.In the function definition you can see a call to fact(n-1)
, this means the function itself is called again.
int fact(int n) //return value is an integer, name of function is "fact", input argument is an integer named n
{
if (n <= 1) // if the input arg equals 1, return 1
return 1;
else
return n * fact(n - 1); //else, return n (input arg of this fact) times the return value of fact(n - 1)
}
Fact(3) 应该返回 3 * 2 * 1 = 6.处理语句 int a = fact(3)
时会发生什么:
Fact(3) is supposed to return 3 * 2 * 1 = 6. What happens when process the statement int a = fact(3)
is the following:
fact(3) //dive into this function:
{
if (n <= 1) //n is not 1
return 1;
else
return n * fact(n - 1); //now we call fact(2)
}
我们称之为事实(2):
we call fact(2):
{
if (n <= 1) //n is not 1
return 1;
else
return n * fact(n - 1); //now we call fact(1)
}
我们称之为事实(1):
we call fact(1):
{
if (n <= 1) //n equals 1
return 1; //return 1
else
return n * fact(n - 1);
}
现在函数 fact(1)
返回 1 到它被调用的点,它在 fact(2)
内部.准确地说,对于语句return 2*fact(1);
,这将被传递回语句return 3*fact(2);
,它被传递回我们的初始函数调用和我们的整数 'a' 得到值 6.
Now function fact(1)
returns 1 to the point where its called, which is inside fact(2)
.To be precise, to the statement return 2*fact(1);
, this gets passed back to the statement return 3*fact(2);
which gets passed back to our initial function call and our integer 'a' gets the value 6.
我希望这对您来说更清楚,如果您仍有问题,请随时提出.
I hope this made it more clear to you, if you have still questions left feel free to ask.
这篇关于理解递归如何在 C 中工作的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!