c语言斐波那契数列求前n项和
时间: 2023-11-22 22:48:27 浏览: 108
数列前n项和的求和公式.doc
以下是C语言求斐波那契数列前n项和的代码:
```c
#include <stdio.h>
int fbi(int n) // 求斐波那契数列第n项的值
{
if (n == 1 || n == 2)
return 1;
else
return fbi(n - 1) + fbi(n - 2);
}
int sum_fbi(int x) // 求斐波那契数列前x项的和
{
if (x <= 0)
return 0;
int s = 0;
for (int i = 1; i <= x; i++)
{
s += fbi(i);
}
return s;
}
int main()
{
int x = 6;
printf("斐波那契数列前15项为:");
for (int i = 1; i <= 15; i++)
{
printf(" %d ", fbi(i));
}
printf("\n");
printf("斐波那契数列前%d项和为%d", x, sum_fbi(x));
return 0;
}
```
阅读全文