斐波那契函数c++递推式
时间: 2023-06-15 17:08:24 浏览: 107
C语言实现斐波那契数列(递归)
斐波那契数列的递推式为:f(n) = f(n-1) + f(n-2),其中f(0)=0,f(1)=1。
以下是C++代码示例:
```cpp
#include <iostream>
using namespace std;
int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;
cout << "输入斐波那契数列项数: ";
cin >> n;
cout << "斐波那契数列: ";
for (int i = 1; i <= n; ++i) {
if(i == 1) {
cout << t1 << " ";
continue;
}
if(i == 2) {
cout << t2 << " ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << " ";
}
return 0;
}
```
以上代码使用了for循环和三个变量t1、t2和nextTerm来实现斐波那契数列的递推。
阅读全文