c語(yǔ)言斐波那契數(shù)列求和的方法是什么

小億
239
2024-01-04 17:07:35

C語(yǔ)言中斐波那契數(shù)列求和的方法可以通過(guò)循環(huán)或遞歸實(shí)現(xiàn)。

  1. 循環(huán)方法:
#include<stdio.h>

int fibonacci(int n){
    int first = 0;
    int second = 1;
    int sum = first + second;
    for(int i=3; i<=n; i++){
        int temp = first + second;
        sum += temp;
        first = second;
        second = temp;
    }
    return sum;
}

int main(){
    int n;
    printf("請(qǐng)輸入斐波那契數(shù)列的項(xiàng)數(shù):");
    scanf("%d", &n);
    int result = fibonacci(n);
    printf("斐波那契數(shù)列的前%d項(xiàng)和為:%d\n", n, result);
    return 0;
}
  1. 遞歸方法:
#include<stdio.h>

int fibonacci(int n){
    if(n <= 2){
        return 1;
    }else{
        return fibonacci(n-1) + fibonacci(n-2);
    }
}

int fibonacciSum(int n){
    int sum = 0;
    for(int i=1; i<=n; i++){
        sum += fibonacci(i);
    }
    return sum;
}

int main(){
    int n;
    printf("請(qǐng)輸入斐波那契數(shù)列的項(xiàng)數(shù):");
    scanf("%d", &n);
    int result = fibonacciSum(n);
    printf("斐波那契數(shù)列的前%d項(xiàng)和為:%d\n", n, result);
    return 0;
}

以上是兩種常見(jiàn)的方法,循環(huán)方法效率較高,遞歸方法效率較低但代碼簡(jiǎn)潔。

0