我试过实现两种方法递归和动态方法,都花了0秒这意味着没有人在我的电脑更好或者代码中出现错误?这里是这些方法关于算法复杂性的问题
1 //递归
#include <stdio.h>
#include <time.h>
#include <iostream>
using std::cout;
void print(int n){
if (n<0) return ;
cout<<n<<" ";
print(n-1);
}
int main(){
int n=10;
time_t start,end;
double dif;
time(&start);
print(n);
time(&end);
dif=difftime(end,start);
printf("it took you %.21f seconds ",dif);
return 0;
}
2.second方法
#include <iostream>
#include <stdio.h>
#include <time.h>
using namespace std;
void print (int n){
if (n<0) return ;
while (n>=0){
cout<<n--<<endl;
}
}
int main(){
int n=10;
double dif;
time_t start,end;
time(&start);
print(n);
time(&end);
dif=difftime(end,start);
printf("it took you %.21f seconds",dif);
return 0;
}
您可能想要以更高的精度查看定时器来进行分析。 – Extrakun 2010-07-19 13:34:33