2017-02-16 43 views
-3
#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點到達上午10點16分」我希望它說:「最近的發車時間爲9:00和10:16抵達」我沒有得到想要的輸入C

+3

「小時== 1,2,3,4,5,6,7,22,23,24」和「小時= 8」都不代表您認爲他們的意思。 – user2357112

+0

我不明白你的意思?你能詳細說明你想說什麼嗎? –

+0

'hour = 8'將值8賦給變量小時 – bruceg

回答

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,所以你可能想要重新檢查你正在檢查的值。

+0

當我這樣做時出現此錯誤 –

+0

main.c:函數'main'中: main.c:12:173:error:expected expression before '')'token if((hour == 0)||(hour == 1)||(hour == 2)||(hour == 3)||(hour == 4)||(hour = = 5)||(小時== 6)||(小時== 7)||(小時== 22)||(小時== 23)||(小時== 24)||){ ^ 退出狀態1 –

+0

@narusin,這就是'('小時== 24)'後面的'||' - 你只有在需要'或'的情況下才需要。擺脫它,它應該編譯好。 – paxdiablo