用递归方法求 fibonacci数列前 20 项及其这20项的和
时间: 2023-05-01 13:02:14 浏览: 250
使用递归方法求斐波那契数列前20项及其前20项的和。
斐波那契数列:1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765
前20项的和为:17710
相关问题
c语言用递归方法求fibonacci数列前20项之和
在C语言中,递归是一种常用的解决问题的技术,特别适用于计算像Fibonacci数列这样的分治结构问题。Fibonacci数列的第n项是由前两项相加得到的,其前几项通常是0、1、1、2、3、5等。以下是递归方法计算Fibonacci数列前20项之和的一个示例:
```c
#include <stdio.h>
// 递归函数计算Fibonacci数列的第n项
int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
// 函数用于累加Fibonacci数列前20项
long long fib_sum(int n) {
long long sum = 0; // 初始化和为0
for (int i = 0; i < n && i < 20; i++) {
sum += fibonacci(i); // 逐项添加到总和中
}
return sum;
}
int main() {
int n = 20;
printf("The sum of the first %d Fibonacci numbers is: %lld\n", n, fib_sum(n));
return 0;
}
```
采用C语言递归方法求斐波那契数列前20项代码
好的,以下是采用递归方法求斐波那契数列前20项的 C 语言代码:
```c
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
int main() {
// 输出斐波那契数列前20项
for (int i = 0; i < 20; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}
```
其中 `fibonacci` 函数用于递归计算斐波那契数列的第 `n` 项。在主程序中,使用循环输出斐波那契数列的前20项。注意,当 `n` 等于 0 时,斐波那契数列的第0项为0;当 `n` 等于 1 时,斐波那契数列的第1项为1。
阅读全文
相关推荐
















