我没有在C上获得想要的输入

时间:2017-02-16 00:59:50

标签: c

#include "stdio.h"

int main() {

  int hour, min;

  printf("Please insert the time in the 24 hour format (hh:mm): "); //ask user about the the time
  scanf("%d:%d", &hour, &min); Store the time

  printf("%d", hour);//Checking to see what time I get

  if (hour == 1, 2, 3, 4, 5, 6, 7, 22, 23, 24){ //Check if the hour time matches
    printf("The closest departure time is 8:00 am and arriving at 10:16 am");
    return 0;
  }

  else if(hour = 8){//Check if the hour time matches
    printf("The closest departure time is 9:00 am and arriving at 10:16 am");
    return 0;
  }

  return 0;
}

当我输入08:00时,它总是会说,"最近的出发时间是上午8:00到达上午10:16"当我想要它说"最近的出发时间是上午9:00到达上午10:16"

1 个答案:

答案 0 :(得分:2)

行:

if (hour == 1, 2, 3, 4, 5, 6, 7, 22, 23, 24) ...
if (hour = 8) ...

做您认为他们做的事情。在第二个中,这是一个赋值而不是一个检查,所以它在功能上等同于:

hour = 8; if (hour) ...

第一个对于unserstand来说有点棘手,但它涉及使用逗号运算符。表达式a, b表示:评估a并将其丢弃,然后“返回”b

因此,您的第一行基本上是条件列表{(hour == 1), (2), (3), ..., (24)}中的最终条件,或者只是:

if (24) ...  // always true

相反,你需要:

if ((hour == 1) || (hour == 2) || ... || (hour == 24)) ...
if (hour == 8) ...

但是,请记住,如果您需要检查许多不同的值,switch语句通常更可取:

switch (hour) {
    case  1: case  2: case  3: case  4: case  5:
    case  6: case  7: case 22: case 23: case 24: {
        printf ("Closest departure time is 8:00am, arriving at 10:16am");
        return 0;
    }
    case 8: {
        printf ("Closest departure time is 9:00am, arriving at 10:16am");
        return 0;
    }
}

对于一些范围,重新安排代码可以使其更短(无评论):

// start as hour in inclusive range INT_MIN..INT_MAX

if (hour == 8) {
    printf ("Closest departure time is 9:00am, arriving at 10:16am");
    return 0;
}

// now INT_MIN..7 or 9..INT_MAX

if ((hour < 1) || (hour > 24) || ((hour > 7) && (hour < 22))) return 0;

// now 1..7 or 22..24

printf ("Closest departure time is 8:00am, arriving at 10:16am");
return 0;

同时请记住,“正常”(就计算机世界而言,尽管有奇怪的军事标准)24小时制时间从00:00到23:59,所以你可能想要重新审视你的价值观重新检查。