函数调用自身的过程称为递归,相应的函数称为递归函数。理解递归的流行示例是阶乘函数。
阶乘函数: f(n) = n * f(n-1),基本条件:如果n <= 1则f(n)= 1。不要担心我们将讨论什么是基本条件,以及为什么它很重要。
#include <iostream>
using namespace std;
//Factorial function
int f(int n){
/* This is called the base condition, it is
* very important to specify the base condition
* in recursion, otherwise your program will throw
* stack overflow error.
*/
if (n <= 1)
return 1;
else
return n*f(n-1);
}
int main(){
int num;
cout<<"Enter a number: ";
cin>>num;
cout<<"Factorial of entered number: "<<f(num);
return 0;
}
递归和斐波那契数代码示例:
#include <iostream>
void countdown(int n);
int Fib(int i);
int main()
{
countdown(4);
int n;
std::cout << "when n = ";
std::cin >> n;
std::cout << "Fib(n) = " << Fib(n) << std::endl;
return 0;
}
void countdown(int n)
{
using namespace std;
cout << "Counting down ... " << n << endl;
if (n > 0)
{
countdown(n - 1); // function calls itself
}
cout << n << ": Kaboom!\n"; // 递归是先进后出吗
}
int Fib(int i)
{
if ((i == 0) || (i == 1))
{
return 1;
}
else
{
return Fib(i - 1) + Fib(i - 2);
}
}
**直接递归:**当函数调用自身时,它被称为直接递归,我们上面看到的例子是直接递归示例。
**间接递归:**当函数调用另一个函数并且该函数调用这个函数时,这称为间接递归。例如:函数 A 调用函数 B,函数 B 调用函数 A。