C语言 制作数字时钟-为什么我给定的分和秒从0开始?

  • 本文关键字:开始 数字 语言 时钟 c scanf
  • 更新时间 :
  • 英文 :


输入指定时间后,我的分和秒从0开始。谁能指出我代码中的错误?

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main ()
{
int h=0,m=0,s=0,i;
system("cls");
printf("Please enter a time format in HH:MM:SSn ");
scanf("%d%d%d",&h,&m,&s);
start:
for(h;h<24;h++)
{
for(m;m<60;m++)
{
for(s;s<60;s++)
{
system("cls");
printf("nnnttt%d:%d:%d",h,m,s);
if(h<12){printf("AM");}
else {printf("PM"); }
for(double i=0;i<99999999;i++)
{i++;
i--;}
}
s=0;
}
m=0;
}
h=0;
goto start;
getch();
return 0;
}

输入22:23:32,显示从22:0:0开始

输入中的冒号分隔符导致scanf调用失败(在读取h值之后),因为它们不能被解释为整数(如%d格式说明符所期望的那样)。

如果您知道您的时间输入将始终有两个:字符分隔小时,分钟和秒值,那么您可以将这些包含在您传递给scanf的格式字符串中-然后将查找(并跳过)整数输入之间的字符。

另外,您应该养成总是检查scanf的返回值的习惯,看看它是否成功地读取了所需的字段数:

//...
int check = scanf("%d:%d:%d", &h, &m, &s);
if (check != 3) { // Failed to read three integers
printf("Invalid input!n");
return 1;
}
//...

您需要修改您的格式字符串以匹配您的输入,并检查scanf()的返回值以确保您实际读取了您期望的数据。您可能希望在使用AM/PM时打印h % 12。我建议你使用sleep而不是busy循环:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main () {
printf("Please enter a time format in HH:MM:SSn ");
int h, m, s;
if(scanf("%d:%d:%d",&h,&m,&s) != 3) {
printf("scanf failedn");
return 1;
}
for(;;) {
for(;h<24;h++) {
for(;m<60;m++) {
for(;s<60;s++) {
printf("nnnttt%02d:%02d:%02d %s",
h % 12,m,s,h < 12 ? "AM" : "PM");
sleep(1);
}
s=0;
}
m=0;
}
h=0;
}
}

和示例:

Please enter a time format in HH:MM:SS
13:2:3

01:02:03 PM

01:02:04 PM

下一步是设置一个定时定时器,因为sleep()在运行足够长的时间时会发生倾斜。如果您可以使用strptime()strftie(),请使用它们。

感谢@AllanWind提供了正确的用户输入代码,下面的代码没有完全相同的缩进级别,并且已经适应了Windows环境。

#include <stdio.h>
#include <windows.h>
int main () {
printf( "Enter a time (format HH:MM:SS)n ");
int h, m, s;
if( scanf( "%d:%d:%d", &h, &m, &s ) != 3 ) {
printf("scanf failedn");
return 1;
}

for( int ds = ((h*60)+m)*60+s; ;ds = (ds+1)%(24*60*60) ) {
printf( "%02d:%02d:%02dn", ds/(60*60), (ds/60)%60, ds%60 );
Sleep( 1000 ); // NB: Uppercase func name and time in mS...
}
return 0;
}
23:59:57
23:59:58
23:59:59
00:00:00
00:00:01
00:00:02

程序应该给处理器一些练习,通过计算每天86400秒的商和模余数…只要稍微调整一下小时值,计数器就可以简单地往上数,在接下来的136年里往上数(作为一个无符号的4字节整数)

相关内容

最新更新