2015-08-28 89 views
0

所以我有一個控制玩家轉向的函數,我希望它在玩家轉彎失敗時返回FAILURE。 (遊戲連接4)。我很明顯希望它在回合成功時能夠成功,但是......即使當我返回成功時,也需要兩次返回成功才能返回一次成功。下面是代碼:我在函數內的第一個返回值沒有返回任何東西

enum input_result take_turn(struct player * current, 
    enum cell_contents board[][BOARDWIDTH]) 
{ 
/***************** Logic for Human player ******************/ 
if(current->type == HUMAN) 
{ 
    printf("human"); 
    return SUCCESS; 
} 

/**************** Logic for Computer player ****************/ 
else if(current->type == COMPUTER) 
{ 
    printf("computer"); 
    return SUCCESS; 
} 
return SUCCESS; 
} 

而且它是由這家名爲:

struct player * play_game(struct player * human , 
    struct player* computer) 
{ 
while(counter < 30) 
{ 
    take_turn(current, board); 

    /* Only swap if take turn was success */ 
    if(take_turn(current, board) == SUCCESS) 
    { 
     swap_players(&current, &other); 
     display_board(board); 
    } 

    counter++; 
} 

return NULL; 
} 

我覺得可能毀掉這樣做的唯一的事情就是我的:

enum input_result 
{ 
/** 
* the input was valid 
**/ 
SUCCESS, 
/** 
* the input was not valld 
**/ 
FAILURE, 
/** 
* the user requested to return to the menu either by pressing enter on 
* an empty line or pressing ctrl-d on an empty line 
**/ 
RTM=-1 
}; 

我不確定爲什麼take_turn(current,board)被調用兩次,當唯一可能的結果是輸入if語句時,因爲每個可能的返回值都是SUCCESS。有誰知道爲什麼會發生這種情況? 我的輸出打印:

HumanHuman

ComputerComputer

HumanHuman

ComputerComputer

等等...這表明它經歷了兩次被註冊成功了。

+0

只是爲了澄清:你想知道爲什麼'take_turn'仍然在if子句中執行,儘管它只能返回'SUCCESS'並且if子句中的代碼**必須被執行? – Downvoter

+0

是的,我想知道爲什麼它沒有進入if語句,並且在返回唯一可能的返回值時調用玩家交換是成功的 – Rrr

+0

我已經投票決定關閉這個問題,因爲這個問題不能成爲印刷錯誤重複(一旦OP刪除額外的呼叫'take_turn()'。 – mah

回答

1

你的問題是在這裏:

while(counter < 30) 
{ 
    take_turn(current, board); 

    /* Only swap if take turn was success */ 
    if(take_turn(current, board) == SUCCESS) 

你打電話take_turn()兩次。

+0

我沒有意識到,如果在這樣的if語句會再次調用它...我不能相信我只花了3個小時試圖解決這個問題...... duhhhhhh 非常感謝 – Rrr

+0

當Op的問題沒有說明他是如何得到上述輸出結果的時候,你是如何得出這個結論的?或者我只是碰巧誤讀了這個問題? –

+0

@rahultyagi它是一個邏輯上解釋了OP說他的輸出包含了什麼,以及他爲什麼認爲這是錯誤的。他顯示了這個代碼es輸出,他不期望輸出......代碼證明它雖然。 – mah

1

您是否注意到您在循環中調用了兩次take_turn?一旦沒有尋找返回值,而另一個在你的if語句中。擺脫第一個。

+0

感謝搶劫,實際上解決了它! – Rrr

相關問題