递归方法求斐波那契数
int fun(int n)
{
int num = 0;
if (n <= 2)
{
num = 1;
return num;
}
else
return fun(n - 1) + fun(n -2);
}
int main()
{
int n = 30;
for (int i = 1; i <=n; i++)
{
printf("%d ", fun(i));
}
system("pause");
return 0;
}
非递归方法求斐波那契数
int fun(int n)
{
int a = 1;
int b = 1;
int result = 0;
if (n <= 2)
return 1;
else
{
for (int i= 3; i<= n; i++)
{
result = a + b;
a = b;
b = result;
}
return result;
}
}
int main()
{
int n = 30;
for (int i = 1; i <= n; i++)
{
printf("%d ", fun(i));
}
system("pause");
return 0;
}
转自:https://blog.csdn.net/weixin_36229332/article/details/78445792