使用递归实现斐波那契数列

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何使用递归创建一个 C 程序来打印斐波那契数列。斐波那契数列定义为每个数字都是前两个数字之和的数列,其中 1, 1 是数列的前两个元素。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c(("`C`")) -.-> c/FileHandlingGroup(["`File Handling`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") c/FunctionsGroup -.-> c/recursion("`Recursion`") c/FileHandlingGroup -.-> c/create_files("`Create Files`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/function_declaration -.-> lab-123248{{"`使用递归实现斐波那契数列`"}} c/recursion -.-> lab-123248{{"`使用递归实现斐波那契数列`"}} c/create_files -.-> lab-123248{{"`使用递归实现斐波那契数列`"}} c/user_input -.-> lab-123248{{"`使用递归实现斐波那契数列`"}} c/output -.-> lab-123248{{"`使用递归实现斐波那契数列`"}} end

创建一个新的 C 文件

~/project/ 目录下创建一个名为 main.c 的 C 文件。

包含必要的库

包含必要的标准输入输出库 stdio.h

#include<stdio.h>

定义 printFibo 函数

定义一个名为 printFibo 的函数,参数为 aj。该函数用于打印斐波那契数列。

void printFibo(int aj)
{
    static long int first = 0, second = 1, sum;
    if(aj > 1)
    {
        sum = first + second;
        first = second;
        second = sum;
        printf("%ld ", sum);
        printFibo(aj-1);    // 递归调用
    }
    else
    {
        // 在元素之后,换行
        printf("\n\n\n");
    }
}

定义 main 函数

定义 main 函数。从用户处获取斐波那契数列的总元素数,并将其传递给 printFibo 函数。

int main()
{
    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
    int k, n;
    long int i = 0, j = 1;
    printf("Enter the length of the Fibonacci series: ");
    scanf("%d", &n);
    printf("\n\nFirst %d terms of the Fibonacci series are:\n\n\n",n);
    printf("%d ", 1);
    printFibo(n);
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

完成代码

以下是使用递归打印斐波那契数列的完整程序:

#include<stdio.h>

// 声明函数
void printFibo(int);

int main()
{
    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
    int k, n;
    long int i = 0, j = 1;
    printf("Enter the length of the Fibonacci series: ");
    scanf("%d", &n);
    printf("\n\nFirst %d terms of the Fibonacci series are:\n\n\n",n);
    printf("%d ", 1);
    printFibo(n);
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

void printFibo(int aj)
{
    static long int first = 0, second = 1, sum;
    if(aj > 1)
    {
        sum = first + second;
        first = second;
        second = sum;
        printf("%ld ", sum);
        printFibo(aj-1);    // 递归调用
    }
    else
    {
        // 在元素之后,换行
        printf("\n\n\n");
    }
}

总结

在本实验中,你学习了如何使用递归创建一个 C 程序来打印斐波那契数列。你现在已经掌握了定义函数以及利用递归遍历所需数列的过程。

您可能感兴趣的其他 C 教程