c语言怎么编写斐波那契数列

   2024-10-02 4400
核心提示:在C语言中,可以通过递归或迭代的方式编写斐波那契数列。以下是两种方法的示例代码:递归方式:#include stdio.hint fibonacci(i

在C语言中,可以通过递归或迭代的方式编写斐波那契数列。以下是两种方法的示例代码:

递归方式:
#include <stdio.h>int fibonacci(int n) {    if (n <= 1) {        return n;    } else {        return fibonacci(n-1) + fibonacci(n-2);    }}int main() {    int n;    printf("Enter the number of terms: ");    scanf("%d", &n);        printf("Fibonacci Series: ");    for (int i = 0; i < n; i++) {        printf("%d ", fibonacci(i));    }        return 0;}
迭代方式:
#include <stdio.h>int main() {    int n, first = 0, second = 1, next;        printf("Enter the number of terms: ");    scanf("%d", &n);        printf("Fibonacci Series: ");        for (int i = 0; i < n; i++) {        if (i <= 1) {            next = i;        } else {            next = first + second;            first = second;            second = next;        }        printf("%d ", next);    }        return 0;}

以上是两种在C语言中编写斐波那契数列的方法,您可以根据自己的需求选择其中一种。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号