本文主要是介绍分别使用递归方法和非递归方法求斐波那契数列,并比较两者的运行速度(测量代码运行时间),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
由运行时间可知,当数据量增大时,递归方法程序运行效率成为瓶颈,速度变得极为缓慢。
#include<cstdio>
#include<iostream>
#include<time.h>
using namespace std;
int Funct( int n )
{if(n==0) return 1;if(n==1) return 1;return Funct(n-1) + Funct(n-2);
}
int Foo( int n ) // n 为非负整数
{int first=1;//应该初始化a为1而不是0int second=1;int first_plus_second;if(n==0) first_plus_second=1;else if(n==1) first_plus_second=1;else for(int i=2;i<=n;i++) //应该n从2开始算起{first_plus_second=first+second;first=second;second=first_plus_second;}return first_plus_second;
}
void testRunningTime()
{int n;long now=0;cout<<"请输入:\n";while(cin>>n){now=clock();
这篇关于分别使用递归方法和非递归方法求斐波那契数列,并比较两者的运行速度(测量代码运行时间)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!