【发布时间】:2015-01-05 03:32:20
【问题描述】:
我正在从 C Programming: A Modern Approach 一书中学习 C 语言中的函数。它包含以下功能:
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 函数中的参数匹配?
* 符号是否意味着 fact(n) 中的 n 现在是 3 - 1 并且它基本上表示它会重新做一遍?
【问题讨论】:
-
@tacocat 你一定会喜欢this 链接。这是追溯递归的方法。
-
这个链接也可以帮助你理解递归:stackoverflow.com/questions/27768992/… :-)