#include "stdio.h"
#include <time.h>
void hannota(int n,char ta1,char ta2,char ta3);
void main()
{
int n;
clock_t begin, duration;
printf("input the number of diskes:");
scanf("%d",&n);
begin = clock();
hannota(n,'1','2','3');
duration = clock() - begin;
printf( "用时约: %d毫秒", duration*1000 / CLOCKS_PER_SEC );
printf("\n");
}
void hannota(int n,char ta1,char ta2,char ta3)
{
if(n==1)
printf("%c--->%c",ta1 ,ta2);
else
{
hannota(n-1,ta1,ta3,ta2);
printf("%c---->%c",ta1,ta2);
hannota(n-1,ta3,ta2,ta1);
}
#include <time.h>
void hannota(int n,char ta1,char ta2,char ta3);
void main()
{
int n;
clock_t begin, duration;
printf("input the number of diskes:");
scanf("%d",&n);
begin = clock();
hannota(n,'1','2','3');
duration = clock() - begin;
printf( "用时约: %d毫秒", duration*1000 / CLOCKS_PER_SEC );
printf("\n");
}
void hannota(int n,char ta1,char ta2,char ta3)
{
if(n==1)
printf("%c--->%c",ta1 ,ta2);
else
{
hannota(n-1,ta1,ta3,ta2);
printf("%c---->%c",ta1,ta2);
hannota(n-1,ta3,ta2,ta1);
}
}
clock()函数返回的是程序执行到现在所经过的cpu时钟数,俗称滴答数,在测试前后用
begin = clock();
// 调用被测时函数
duration = clock() - begin;
就能获得这期间这个函数或这段代码执行所用掉的时钟数,然后可以用用它来除以CLOCKS_PER_SEC就可以转换成秒
duration / CLOCKS_PER_SEC
duration的单位是CLOCKS,所以除一下就转成秒了,CLOCKS_PER_SEC这是个time.h里定义的常量,在不同机器和编译器里值可能不同。
转成秒以后接下来到分钟、小时的转换也就很简单了。。。