C++递归和斐波那契数

函数调用自身的过程称为递归,相应的函数称为递归函数。理解递归的流行示例是阶乘函数。

阶乘函数: 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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值