What is the method of summing the Fibonacci sequence in the C language?
In C language, the sum of the Fibonacci sequence can be achieved through either loops or recursion.
- loop method:
#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("请输入斐波那契数列的项数:");
scanf("%d", &n);
int result = fibonacci(n);
printf("斐波那契数列的前%d项和为:%d\n", n, result);
return 0;
}
- Recursive method:
#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("请输入斐波那契数列的项数:");
scanf("%d", &n);
int result = fibonacciSum(n);
printf("斐波那契数列的前%d项和为:%d\n", n, result);
return 0;
}
The above are two common methods, with the iterative method being more efficient and the recursive method being less efficient but having simpler code.