在我的 mac 上每次增量后都会打印多次此代码。我无法使用还有其他方法可以解决这个问题吗?
用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;
}
Made a digital clock using C program :
This is a simple digital clock i made and the issue i am having is that every time the time gets incremented the printf gets printed . Since i am on mac i cant use <conio.h> .
My expectation : I want the program to display a single printf and the increment happens in a single printf instead of new printf every time the time changes.
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新:我确实在 printf 中进行了更改,并且得到了我想要的内容
更新前:
更新后:
Update : I did change in printf and i got what i was looking for
Before update :
After update :
您需要对输入的时间进行更彻底的错误检查(如果用户输入负值,或者等于 60 的分钟或秒怎么办);要获得在单行上打印的时间,您需要将
\n
替换为\r
,并刷新stdout
。要根据系统的实时时钟获得更强大且计时更精确的时钟,请尝试以下
操作:查看
time
、localtime
、和 strftime 来看看它是如何工作的,但基本上它从系统时钟获取时间,如果自上次打印以来它发生了变化,则格式化并打印它。You need more thorough error checking on the time entered (what if the user enters negative values, or minutes or seconds equal to 60); and to get the time to print on a single line, you need to replace the
\n
with a\r
, and to flushstdout
.To get a clock that is more robust and with more precise timing, based on your system's real-time clock, try this:
Look at the man pages for
time
,localtime
, andstrftime
to see how this works, but basically it gets the time from the system clock, and if it has changed since the last time it was printed, format it and print it.