使用C程序制作了一个数字时钟:这是我制作的一个简单的数字时钟,我的问题是,每次增加时间,就会打印printf。因为我在mac上,所以我不能使用。
我的期望:,我希望程序显示单个printf,每次变化时,递增都发生在单个printf中,而不是新printf。
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h >
int main()
{
int h, m , ;
int d=1;
printf("Enter the time : ");
scanf("%d%d%d", &h,&m,&s);
if(h>12 || m>60 || s>60){
printf("ERROR!!");
exit(0);
}
while(1){
s++;
if(s>59){
m++;
s=0;
}
if(m>59){
h++;
m=0;
}
if(h>12){
h=1;
}
printf("\n Clock ");
printf(" %02d:%02d:%02d",h, m ,s);
sleep(1);
}
return 0;
} 发布于 2022-03-20 16:17:09
您需要对输入的时间进行更彻底的错误检查(如果用户输入负值或分钟或秒等于60);要获得在一行上打印的时间,需要用\n替换\r,并刷新stdout。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
unsigned h, m, s;
printf("Enter the time : ");
scanf("%u:%u:%u", &h,&m,&s);
if(h > 12 || h < 1 || m > 59 || m < 0 || s > 59 || s < 0) {
printf("ERROR!!");
exit(0);
}
while (1) {
if (++s > 59) {
s = 0;
if (++m > 59) {
m = 0;
if(++h > 12)
h = 1;
}
}
printf("\r Clock %2u:%02u:%02u", h, m ,s);
fflush(stdout);
sleep(1);
}
return 0;
}为了获得一个更健壮和更精确的时钟,基于您系统的实时时钟,请尝试如下:
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t now;
time_t last_now = -1;
struct tm *tod;
char outbuf[32];
while (1) {
now = time(NULL);
if (now != last_now) {
last_now = now;
tod = localtime(&now);
strftime(outbuf,sizeof outbuf,"%l:%M:%S %P",tod);
printf("\r Clock %s", outbuf);
fflush(stdout);
}
}
return 0;
}查看time、localtime和strftime的手册页,了解它是如何工作的,但基本上它从系统时钟中获得时间,如果它自上次打印后发生了更改,则格式化并打印它。
https://stackoverflow.com/questions/71548195
复制相似问题