#include <iostream>
using namespace std;
void printN(int n)
{
if (n) //over condition 必须要有
{
printN(n - 1);
cout << n<<endl;
}
return;
}
//void printN(int n)
//{
// int i;
// for (i = 1; i <=n; i++)
// {
// cout << i<<endl;
// }
//}
int main()
{
int n;
cin >> n;
printN(n);
return 0;
}
改进版:测算时间;且将一个函数作为另一个函数的参数
#include <iostream>
#include <time.h>
using namespace std;
#define maxk 10
clock_t start, stop;
double duration;
void time(int n, void(*p)(int));
void printN1(int n)
{
if (n) //over condition 必须要有
{
printN1(n - 1);
cout << n << endl;
}
//return;
}
void printN2(int n)
{
int i;
for (i = 1; i <=n; i++)
{
cout << i<<endl;
}
}
int main()
{
int n;
cin >> n;
time(n, printN2);
return 0;
}
void time(int n,void (*p)(int))
{
start = clock();
for (int i = 0; i < maxk; i++)
{
p(n);
}
stop = clock();
duration = (double)(stop - start) / CLK_TCK / maxk;
printf("ticks=%f\n", (double)(stop - start));
printf("dura=%6.2e\n", duration);
}