编写程序计算Fibonacci数列的前x项
时间: 2024-06-14 13:04:39 浏览: 61
Java Fibonacci 平均成绩 笛卡尔坐标系
以下是一个计算Fibonacci数列前x项和的C++程序示例:
```cpp
#include <iostream>
using namespace std;
int fbi(int n) {
if (n <= 0)
return 0;
if (n == 1 || n == 2)
return 1;
int a = 1, b = 1, c;
for (int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
int sum_fbi(int 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;
cout << "斐波那契数列前15项为:";
for (int i = 1; i <= 15; i++) {
cout << " " << fbi(i);
}
cout << endl;
cout << "斐波那契数列前" << x << "项和为" << sum_fbi(x) << endl;
system("pause");
return 0;
}
```
阅读全文