我目前正在用C创建一个闹钟。它的要点非常简单,我想:
然而,我遇到了一些麻烦,现在已经停留了一段时间。这是我到目前为止所做的:
int u_input(int* uhour, int* uminute, int* usecond);
void sc_alarm();
int main(int argc, char *argv[])
{
int uhour, uminute, usecond;
u_input(&uhour, &uminute, &usecond);
sc_alarm(uhour, uminute, usecond);
}
int u_input(int* uhour, int* uminute, int* usecond)
{
printf("Enter H M S:");
scanf("%d %d %d", uhour, uminute, usecond);
}
void sc_alarm(int uhour, int uminute, int usecond)
{
struct tm *tm;
time_t ctime;
ctime = time(NULL);
tm = localtime(&ctime);
int difference, alarm_total, local_time_total;
int chour = tm->tm_hour;
int cminute = tm->tm_min;
int csecond = tm->tm_sec;
difference = alarm_total - local_time_total;
alarm_total = (uhour * 3600) + (uminute * 60) + usecond;
local_time_total = (chour * 3600) + (cminute * 60) + csecond;
do
{
printf("Time left: %d seconds\n",difference);
difference--;
sleep(1);
}
while(difference > 0);
printf("Alarm!\n");
}
答案 0 :(得分:0)
您正在计算需要减去的值之前的差异。
替换
difference = alarm_total - local_time_total;
alarm_total = (uhour * 3600) + (uminute * 60) + usecond;
local_time_total = (chour * 3600) + (cminute * 60) + csecond;
带
alarm_total = (uhour * 3600) + (uminute * 60) + usecond;
local_time_total = (chour * 3600) + (cminute * 60) + csecond;
difference = alarm_total - local_time_total;
另外,你应该注意,如果你在Windows上,sleep
以毫秒为单位获取它的参数,如果你在Linux或Unix上sleep
接受它的参数在几秒钟内,您需要相应地修改sleep
功能。