C语言编写时钟程序
实现时钟的基本功能
在C语言中,时钟程序可以通过调用time.h头文件中的函数来获取当前系统时间,并在控制台输出。以下是基本的时钟程序代码:
```c
#include
#include
int main() {
time_t now;
struct tm *tm;
char buf[64];
while(1) {
now = time(NULL);
tm = localtime(&now);
strftime(buf, sizeof(buf), \"%Y-%m-%d %H:%M:%S\", tm);
printf(\"%s\
\", buf);
sleep(1);
}
return 0;
}
```
此代码可以在控制台每秒钟输出一次当前系统时间。
增加定时器功能
我们可以在基本时钟程序的基础上增加一个计时器功能。当用户输入一段时间后,计时开始倒数,当计时结束后,程序提示用户。以下是代码示例:
```c
#include
#include
#include
int main() {
time_t now, end;
struct tm *tm;
char buf[64], input[10];
int hour, min, sec, count;
printf(\"请输入倒计时时间,格式为:小时:分钟:秒\
\");
scanf(\"%d:%d:%d\", &hour, &min, &sec);
if(hour < 0 || min < 0 || sec < 0) {
printf(\"输入错误,请重新输入!\
\");
return -1;
}
count = hour * 3600 + min * 60 + sec;
end = time(NULL) + count;
printf(\"倒计时开始!\
\");
while(1) {
now = time(NULL);
tm = localtime(&now);
strftime(buf, sizeof(buf), \"%Y-%m-%d %H:%M:%S\", tm);
printf(\"当前时间:%s\
\", buf);
if(count <= 0) {
printf(\"倒计时结束!\
\");
break;
}
count = end - now;
printf(\"剩余时间:%d小时 %d分钟 %d秒\
\", count/3600, (count/60)%60, count%60);
sleep(1);
system(\"cls\");
}
return 0;
}
```
该代码可以在用户输入倒计时时间后开始倒计时,直到时间结束提示用户。
增加秒表功能
我们可以在基本时钟程序的基础上增加一个秒表功能。当用户输入开始后,计时器开始计时,用户可以随时停止并输出时间。以下是代码示例:
```c
#include
#include
#include
int main() {
time_t now, start, end;
struct tm *tm;
char buf[64], input[1];
int sec = 0;
printf(\"输入s开始计时,输入q结束计时\
\");
while(1) {
scanf(\"%s\", input);
if(input[0] == 's') {
start = time(NULL);
printf(\"计时开始!\
\");
}
else if(input[0] == 'q') {
end = time(NULL);
sec = end - start;
tm = localtime(&start);
strftime(buf, sizeof(buf), \"%Y-%m-%d %H:%M:%S\", tm);
printf(\"计时开始时间:%s\
\", buf);
tm = localtime(&end);
strftime(buf, sizeof(buf), \"%Y-%m-%d %H:%M:%S\", tm);
printf(\"计时结束时间:%s\
\", buf);
printf(\"计时时间:%d秒\
\", sec);
break;
}
else {
printf(\"输入有误,请重新输入!\
\");
}
}
return 0;
}
```
该代码可以实现一个简单的秒表功能,用户可以在输入s键开始计时,q键结束计时并输出时间。
至此,我们完成了一个基本的时钟程序,并增加了定时器和秒表功能。这个程序可以在控制台中运行,如果需要实现图形界面,可以使用C语言库中的图形界面库。
本文内容来自互联网,请自行判断内容的正确性。若本站收录的内容无意侵犯了贵司版权,且有疑问请给我们来信,我们会及时处理和回复。 转载请注明出处:
http://www.ziy123.com/jfss/3551.html
C语言时钟代码(C语言编写时钟程序)