编程写个计时器怎么写

时间:2025-01-27 08:57:32 网络游戏

编写计时器的方法取决于你使用的编程语言。以下是几种常见编程语言的计时器示例代码:

Python

简单倒计时计时器

```python

import time

def countdown(seconds):

while seconds > 0:

print(f"Time left: {seconds} seconds")

time.sleep(1)

seconds -= 1

print("Time's up!")

获取用户输入

countdown_time = int(input("Enter the countdown time in seconds: "))

countdown(countdown_time)

```

计时器函数

```python

import time

def start_timer():

start_time = time.time()

return start_time

def stop_timer(start_time):

end_time = time.time()

elapsed_time = end_time - start_time

return elapsed_time

def format_time(elapsed_time):

minutes = int(elapsed_time // 60)

seconds = int(elapsed_time % 60)

milliseconds = int((elapsed_time % 1) * 1000)

return f"{minutes:02d}:{seconds:02d}:{milliseconds:03d}"

def main():

input("按Enter开始计时...")

start_time = start_timer()

input("按Enter停止计时...")

elapsed_time = stop_timer(start_time)

formatted_time = format_time(elapsed_time)

print("计时结果:", formatted_time)

if __name__ == "__main__":

main()

```

C语言

```c

include

include

void update(struct timespec *timer) {

clock_gettime(CLOCK_REALTIME, timer);

}

void display(struct timespec *timer) {

time_t seconds = timer->tv_sec;

struct tm *timeinfo = localtime(&seconds);

printf("%02d:%02d:%02d\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);

}

void delay(int milliseconds) {

usleep(milliseconds * 1000);

}

int main() {

struct timespec timer;

update(&timer);

delay(9000000); // 延迟9000000微秒,约等于1秒

display(&timer);

return 0;

}

```

JavaScript (HTML + JS)

```html

简易计时器