斐波那契数列c++实现
时间: 2024-06-12 18:02:56 浏览: 176
斐波那契数列是一个经典的数学序列,其中每个数字是前两个数字的和,通常从0和1开始,即F(0) = 0, F(1) = 1,后续项为F(n) = F(n-1) + F(n-2)。在C++中实现斐波那契数列有多种方法,这里我会演示两种常见的实现方式:
1. 递归实现(虽然不推荐,因为效率低)
```cpp
#include <iostream>
int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "Fibonacci number at position " << num << " is: " << fibonacci(num);
return 0;
}
```
2. 迭代实现(更高效)
```cpp
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1)
return n;
int fib[n+1];
fib = 0;
fib = 1;
for (int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Fibonacci number at position " << num << " is: " << fibonacci(num);
return 0;
}
```
阅读全文