斐波那契数列:1、1、2、3、5、8、13、21、34,斐波那契数列以如下被以递推的方法定义:F(1)=1,F(2)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 3,n ∈ N*)
#include <iostream>
using namespace std;
int Fib(int n)
{
if (n <= 2) return 1;
else return Fib(n-1) + Fib(n - 2);
}
int main()
{
//1 1 2 3 5 8 13 21.....
int a = 1, b = 1, n, i=0;
cout << "请输入n的值:";
cin >> n;
cout << "非递归方法:";
if (n == 1) cout << a << " ";
else
{
cout << a << " " << b<<" ";
while (i < int(n / 2)-1)
{
a = a + b;
b = a + b;
cout << a << " " << b<<" ";
i++;
}
if (n % 2 != 0) cout << a + b;
}
cout << "\n递归方法(只输出了最后一个):";
cout << Fib(n) << endl;
return 0;
}
运行结果: