如何用C++编写一个函数来计算斐波那契数列?
时间: 2024-12-14 08:15:21 浏览: 9
fibonacci-numbers-cpp:命令行应用程序生成斐波那契数
在C++中,我们可以使用递归或循环结构来编写一个计算斐波那契数列的函数。这里分别给出递归和非递归(迭代)两种方法:
### 1. 使用递归
```cpp
#include <iostream>
// 递归版本的斐波那契函数
int fibonacci_recursive(int n) {
if (n <= 1)
return n;
else
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
int main() {
int num;
std::cout << "Enter a number to calculate Fibonacci: ";
std::cin >> num;
std::cout << "Fibonacci of " << num << " is: " << fibonacci_recursive(num) << std::endl;
return 0;
}
```
### 2. 使用循环
```cpp
#include <iostream>
// 非递归版本的斐波那契函数
int fibonacci_iterative(int n) {
if (n <= 1)
return n;
int fib_n_minus_1 = 0, fib_n_minus_2 = 1, current_fib = 0;
for (int i = 2; i <= n; ++i) {
current_fib = fib_n_minus_1 + fib_n_minus_2;
fib_n_minus_1 = fib_n_minus_2;
fib_n_minus_2 = current_fib;
}
return current_fib;
}
int main() {
int num;
std::cout << "Enter a number to calculate Fibonacci: ";
std::cin >> num;
std::cout << "Fibonacci of " << num << " is: " << fibonacci_iterative(num) << std::endl;
return 0;
}
```
阅读全文