斐波纳契数列
注意事项:
斐波那契数列增长的速度很快,高于几何级。超过40级的数列值很可能突破4GB的取值范围,从而发生溢出。
其隐式和显式求解的结果是不同的,必须在显式求解的基础上对计算结果进行取整修正。
代码1:用迭代的方法实现斐波那数列。
#include<stdio.h>
main()
{
Long fn1,fn2,fn3;
int i,n;
printf("Please anter month number(less than 40):");
scanf("%d",&n);
if(n<1) n=1;
printf("\n");
fn1=fn2=1;
printf(" M. 1:%10d",fn1);
if(n>1)
printf(" M. 2:%10d",fn2);
for(i=3;i<=n;i++)
{
fn3=fn2+fn1;
printf(" M.%2d:%10d",i,fn3) ;
if(i%4==0)
printf("\n");
fn1=fn2;
fn2=fn3;
}
getch();
}
代码2:用使用公式法实现斐波那契数列。
#include<stdio.h>
#include<math.h>
main()
{
int n;
printf("Please input the number of n:\n");
scanf("%d",&n);
printf("%d\n",n);
printf("f%d=%lf",n,pow((1+pow(5,0.5))/2,n));
getch();
}
代码3:验证斐波那契数列性质,前后元素的比例符合黄金分割。
#include<stdio.h>
#define Limit 40
main()
{
long f0=0,f1=1,n,temp;
printf("%7s%19s%29s\n%7s%19s%29s\n%7s%19s%29s\n",
" ","Fibonacci","Fibonacci",
" n"," number","quotient",
"--","-------","--------");
printf("%7d%19d\n%7d%19d\n",0,0,1,1);
for(n=2;n<=Limit;n++)
{
temp=f1;
f1+=f0;
f0=temp;
printf("%7d%19d%29.16f\n",n,f1,(double)f1/f0);
}
return 0;
}