c++ 斐波那契数列
时间: 2023-11-29 09:47:33 浏览: 125
以下是C++实现斐波那契数列的两种方法:
1.使用递归实现斐波那契数列
```c++
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 10;
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
return 0;
}
```
2.使用循环实现斐波那契数列
```c++
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1) {
return n;
}
int a = 0, b = 1;
for (int i = 2; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
int main() {
int n = 10;
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
return 0;
}
```
阅读全文