我目前正在用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");

}

最佳答案

您正在计算需要减去的值之前的差。

更换

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函数。

关于c - 如何通过用户输入来实现闹钟?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38114476/

10-09 15:22