c++求斐波那契数列
时间: 2024-01-16 10:17:01 浏览: 95
以下是三种C++实现斐波那契数列的方法:
1.数组实现
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a[10000] = {1, 1};
for (int i = 2; i < n; i++) {
a[i] = a[i - 1] + a[i - 2];
}
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
return 0;
}
```
2.递归实现
```c++
#include <iostream>
using namespace std;
int fib(int n) {
if (n == 0 || n == 1) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cout << fib(i) << " ";
}
return 0;
}
```
3.动态规划实现
```c++
#include <iostream>
using namespace std;
int fib(int n) {
int a = 1, b = 1;
for (int i = 2; i < n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cout << fib(i) << " ";
}
return 0;
}
```
阅读全文