2014-10-10 80 views
0

我遇到了一個問題,而我已經寫了一個岩石,紙張,剪刀遊戲的while循環。它永遠不會出現循環。我嘗試了一切,但似乎沒有任何工作。一切看起來都合乎邏輯,但也許我錯過了一些東西。有人有主意嗎?雖然我確實知道一個簡單的解決方法是爲每個if聲明添加break,但我想了解爲什麼循環本身不起作用。問題與循環做

#include <stdio.h> 
#include <stdlib.h> 

int main(){ 

int rounds, 
    wins, 
    max; 

do { 
    printf("Best 2 out of 3 or Best 3 out of 5? (Enter 3 or 5)\n"); 
    scanf_s("%d", &rounds); 
    printf("%d\n\n", rounds); 
    if (rounds == 3){ 
     wins = 2; 
     max = 3; 
     puts("OK!"); 
    } 
    else if (rounds == 5){ 
     wins = 3; 
     max = 5; 
     puts("\nOK!"); 
    } 
    else { 
     printf("Please enter a valid option.\n\n"); 
    } 
} while (rounds != 3 || rounds != 5); 

system("pause"); 
} 

回答

3

我用盡了一切辦法,但似乎沒有任何工作。

您試過while (rounds != 3 && rounds != 5);

當然不是!嘗試一下,它會工作。請注意,每個數字不等於3或不等於5,因此條件將始終爲true||

+0

你是對的,它的確如此,但是如果滿足其中一個條件,'||'也不會返回true嗎? – Novaea 2014-10-10 17:43:57

+0

@Novaea;否。請參閱更新。 – haccks 2014-10-10 17:48:26

2

使用AND不是OR

像這樣:

while (rounds != 3 && rounds != 5); 
1

你的停車條件始終爲真。

rounds != 3 || rounds != 5 // || = OR 

對於所有數字都計算爲真。

2

rounds != 3 || rounds != 5始終是真實的 - 無論價值rounds有它並不等於3或5

你想

rounds != 3 && rounds != 5 
4

這就是爲什麼測試(謂語)應在正邏輯寫入。轉換

rounds != 3 || rounds != 5 

!(rounds == 3 && rounds == 5) 

這顯然簡化了

true 

但不心疼德·摩根定律(偶)的應用。 1998年,我修復了這種確切類型的商業桌面業務應用程序的缺陷!

+0

Gotcha。剛纔意識到德摩根法律並沒有被正確地教給我。打開書的時間。 – Novaea 2014-10-10 17:48:48