斐波那契数列,又称黄金数列,指的是这样一个数列:1、1、2、3、5、8、13、21、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(1)=1,F(2)=1,F(n)=F(n-1)+F(n-2)(n>2,n∈N*)。

第一种实现方法可以通过其定义得知:递归

int Fib2(int num)
{
int fib = ; assert(num > ); if(num < )
fib = ;
else
fib = Fib2(num - ) + Fib2(num -); return fib;
}

第二种方法:迭代

int Fib1(int num)
{
int i = ;
int j = ;
int tmp = ;
int index = ; assert(num > ); for(index = ;index < num; index++)
{
tmp = i + j;
i = j;
j = tmp;
}
return tmp;
}

两种方法优劣,运行比较很容易得出

#include<stdio.h>
#include<assert.h> int Fib1(int num)
{
int i = ;
int j = ;
int tmp = ;
int index = ; assert(num > ); for(index = ;index < num; index++)
{
tmp = i + j;
i = j;
j = tmp;
}
return tmp;
} int Fib2(int num)
{
int fib = ; assert(num > ); if(num < )
fib = ;
else
fib = Fib2(num - ) + Fib2(num -); return fib;
} void displayFib(int num)
{
int i = ;
for(i = ; i <= num; i++)
{
printf("%d ",Fib1(i));
}
printf("%\n");
for(i = ; i <= num; i++)
{
printf("%d ",Fib2(i));
}
printf("\n");
} int main()
{
int num = ;
printf("please enter a unsinged int number(enter 0 quit):\n");
scanf("%d",&num);
while(num)
{
displayFib(num);
printf("please enter a unsinged int number(enter 0 quit):\n");
scanf("%d",&num);
}
return ;
}
05-11 13:42