如何通过用户输入来实现闹钟?

时间:2016-06-30 05:16:24

标签: c

我目前正在用C创建一个闹钟。它的要点非常简单,我想:

  1. 获取所需闹钟时间的用户输入
  2. 将其与当地时间进行比较
  3. 以秒为单位递减计时器,并在达到闹钟时打印
  4. 然而,我遇到了一些麻烦,现在已经停留了一段时间。这是我到目前为止所做的:

    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");
    
    }
    

1 个答案:

答案 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功能。

相关问题