當前位置:編程學習大全網 - 編程語言 - C語言,計時器

C語言,計時器

秒表計時器的代碼

#include

<stdio.h>

#include

<conio.h>

#include

<windows.h>

#include

<stdlib.h>

struct

tm

//定義時間結構體,包括時分秒和10毫秒

{

int

hours,minutes,seconds;

int

hscd;

}time,tmp,total;

//time用以計時顯示,tmp用以存儲上壹階段時間,total記總時間

int

cnt;

FILE*

fout;

//每次調用update函數,相當於時間過了10ms

void

update(struct

tm

*t)

{

(*t).hscd++;

//10ms單位時間加1

cnt++;

if

((*t).hscd==100)

//計時滿1s,進位

{

(*t).hscd=0;

(*t).seconds++;

}

if

((*t).seconds==60)

//計時滿壹分,進位

{

(*t).seconds=0;

(*t).minutes++;

}

if

((*t).minutes==60)

//計時滿壹小時,進位

{

(*t).minutes=0;

(*t).hours++;

}

if((*t).hours==24)

(*t).hours=0;

//delay();

Sleep(10);

//Sleep是windows提供的函數,作用是暫停程序,單位毫秒,所以此處暫停10ms

}

void

display(struct

tm

*t)

{

//此處輸出計時結果,\r為回車不換行,既壹直在同壹行更新時間

printf("%d:",(*t).hours);

printf("%d:",(*t).minutes);

printf("%d:",(*t).seconds);

printf("%d\r",(*t).hscd);

//printf("Now,

press

‘e’

key

to

stop

the

clock…");

}

void

time_init()

//初始化時間

{

time.hours=time.minutes=time.seconds=time.hscd=0;

}

void

get_total()

//計算總時間

{

total.hscd

=

cnt

%

100;

cnt

/=

100;

total.seconds

=

cnt

%

60;

cnt

/=

60;

total.minutes

=

cnt

%

60;

cnt

/=

60;

total.hours

=

cnt;

}

int

main()

{

char

m;

time_init();

cnt

=

0;

fout

=

fopen("timeout.txt","w");

printf("按回車鍵開始計時!\n");

while(1)

{

m

=

getch();

if(m

!=

‘\r’)

//讀入壹個輸入,如果是回車,那麽跳出次循環

printf("輸入錯誤,僅能輸入回車鍵!\n");

else

break;

}

printf("已經開始計時,但是妳可以按回車鍵以分段計時!\n");

while(1)

{

if(kbhit())

//此處檢查是否有鍵盤輸入

{

m=getch();

if(m

==

‘\r’)

//如果等於回車,那麽計時結束,跳出循環

break;

else

if(m

==

‘)

//如果等於空格,顯示此次計時,初始化計時器

{

tmp

=

time;

//記錄上壹段計時器結果

fprintf(fout,"%d:%d:%d:%d\n",tmp.hours,tmp.minutes,tmp.seconds,tmp.hscd);

//寫入文件

time_init();

printf("\n");

}

else

{

printf("輸入錯誤,僅支持輸入回車鍵或者空格鍵!\n");

}

}

update(&time);

//更新計時器

display(&time);

//顯示計時器時間

}

tmp

=

time;

//輸出最後壹次即使結果,寫入文件

fprintf(fout,"%d:%d:%d:%d\n",tmp.hours,tmp.minutes,tmp.seconds,tmp.hscd);

get_total();

//計算總的時間,顯示,並寫入文件

printf("\n總時間:%d:%d:%d:%d\n",total.hours,total.minutes,total.seconds,total.hscd);

fprintf(fout,"統計時間:%d:%d:%d:%d\n",total.hours,total.minutes,total.seconds,total.hscd);

fclose(fout);

printf("已經保存到當前目錄下的timeout.txt文件中按任意鍵結束!");

getch();

}

  • 上一篇:本田xrv鑰匙燈閃爍無法啟動是怎麽回事
  • 下一篇:九年級下冊“我用受損的手掌”教案
  • copyright 2024編程學習大全網