斐波拉契级数的几种编程方法
- 提问者网友:星軌
- 2021-07-30 04:07
- 五星知识达人网友:酒安江南
- 2021-07-30 04:17
程序代码:(不含指针)递归和非递归
#include<iostream.h>
#include <ctime>
//算法一(非递归)
void Fib1(int n)
{
double fib1=1,fib2=0,fibn=1;
cout<<"Fib数列的1-"<<n<<"闭区间的元素是:"<<endl;
for(int i=1;i<=n;i++)
{
cout<<fibn<<" ";
fibn=fib1+fib2;
fib2=fib1;
fib1=fibn;
if(i%10==0)cout<<endl;
}
cout<<endl;
}
//算法二(递归)
double Fib21(int n)
{
if(n<=1)return 1;
return(Fib21(n-1)+Fib21(n-2));
}
double Fib2(int n)
{
double y= Fib21(n)-Fib21(n-2);
return 0;
}
void main()
{
int n=0;
cout<<"请输入你要求的fib的个数:";
cin>>n;
//算法一(非递归)
clock_t Start1,Finish1;
Start1=clock();
Fib1(n);
Finish1=clock();
double t1=double(Finish1-Start1)/CLOCKS_PER_SEC;
cout<<"运算结果如下:"<<endl<<"===================================="<<endl;
cout<<"非递归算法运行时间为:"<<t1<<"秒"<<endl<<endl;
cout<<"===================================="<<endl;
//算法二(递归)
clock_t Start2,Finish2;
Start2=clock();
// double y= Fib2(n)-Fib2(n-2);
Fib2(n);
Finish2=clock();
double t2=double(Finish2-Start2)/CLOCKS_PER_SEC;
cout<<"递归算法运行时间为:"<<t2<<"秒"<<endl;
cout<<endl;
}
执行结果: