秒表的程序怎么编写

时间:2025-01-25 09:19:22 单机游戏

编写秒表程序可以使用不同的编程语言和方法。下面我将提供几种不同编程语言的秒表程序示例。

C语言秒表程序示例

```c

include

include

include

int main() {

clock_t start, end, elapsed_time;

int hours, minutes, seconds, cnt;

printf("*This is a stopwatch*\n\n");

printf("Press 'p' to pause.\n");

printf("Press any key to start & to stop.");

getch();

system("cls");

printf("\t\t*This is a stopwatch*\n\n");

start = clock();

cnt = 0;

while (1) {

end = clock();

elapsed_time = (double)(end - start) / CLOCKS_PER_SEC;

hours = (int)(elapsed_time / 3600);

minutes = (int)((elapsed_time % 3600) / 60);

seconds = (int)(elapsed_time % 60);

if (kbhit()) {

if (_kbhit()) { // Check if 'p' is pressed

while (_kbhit()) { // Wait for 'p' to be released

Sleep(100);

}

} else {

break; // Any other key stops the timer

}

}

printf("\rTime -\t %02d : %02d : %02d", hours, minutes, seconds);

cnt++;

Sleep(1000); // Sleep for 1 second

}

printf("\nProgram exited\n");

return 0;

}

```

Python秒表程序示例

```python

import time

def stopwatch():

start_time = time.time()

print('按下回车开始计时, 按下 Ctrl + C 停止计时。')

try:

while True:

elapsed_time = round(time.time() - start_time, 2)

print(f' 计时: {elapsed_time} 秒 ', end='\r')

time.sleep(1)

except KeyboardInterrupt:

end_time = time.time()

total_time = round(end_time - start_time, 2)

print(f'\n计时结束, 总共时间为: {total_time} 秒')

if __name__ == '__main__':

stopwatch()

```

51单片机秒表程序示例