c++ 斐波那契数列第n项的和
时间: 2024-06-14 10:08:18 浏览: 161
C++中计算斐波那契数列第n项的和可以通过循环或递归的方式实现。下面是两种方法的示例代码:
1. 使用循环计算斐波那契数列第n项的和:
```cpp
#include <iostream>
int fibonacciSum(int n) {
if (n <= 0) {
return 0;
}
int sum = 0;
int a = 0;
int b = 1;
for (int i = 1; i <= n; i++) {
int temp = a + b;
a = b;
b = temp;
sum += a;
}
return sum;
}
int main() {
int n;
std::cout << "请输入n的值:";
std::cin >> n;
int sum = fibonacciSum(n);
std::cout << "斐波那契数列第" << n << "项的和为:" << sum << std::endl;
return 0;
}
```
2. 使用递归计算斐波那契数列第n项的和:
```cpp
#include <iostream>
int fibonacci(int n) {
if (n <= 0) {
return 0;
}
else if (n == 1) {
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;
std::cout << "请输入n的值:";
std::cin >> n;
int sum = fibonacciSum(n);
std::cout << "斐波那契数列第" << n << "项的和为:" << sum << std::endl;
return 0;
}
```
希望以上代码能够帮助到你!
阅读全文