温馨提示×

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

小亿
83
2024-08-01 20:10:12
栏目: 编程语言

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

  1. 递归方式:
#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;
}
  1. 迭代方式:
#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语言中编写斐波那契数列的方法,您可以根据自己的需求选择其中一种。

0