2012-01-16 176 views
1

我創建了一個簡單的猜謎遊戲程序。我的問題是,我不知道如何將程序循環回程序的開始,一旦用戶猜錯了一個數字。我希望程序繼續詢問用戶一個號碼,直到他得到正確的答案。有人能幫我嗎?猜測遊戲程序

#include <stdio.h> 

int main (void) { 
    int value = 58; 
    int guess; 

    printf("Please enter a value: "); 
    scanf("%i", &guess); 

    if (guess == value) { 
     printf("Congratulations, you guessed the right value"); 
    } 
    else if (guess > value) { 
     printf("That value is too high. Please guess again: "); 
     scanf("%i", &guess); 
    } 
    else if (guess < value) { 
     printf("That value is too low. Please guess again: "); 
     scanf("%i", &guess); 
    } 

    return 0; 
} 
+0

我想你需要一本好書:http://stackoverflow.com/q/562303/10077 – 2012-01-16 20:58:37

回答

0

使用do { /*your code*/ } while(condition);

do { 
/*your code*/ 
char wannaPlayAgain; 
wannaPlayAgain = getchar(); 
} while(wannaPlayAgain=='y'); 

當然,你應該修復它的情況下,人們輸入Y而不是Y,但問題是,你需要在做包裝你的程序while循環(它會執行至少一次)或一段時間循環(在輸入條件之前獲取初始值)以及初始啓動條件。

1

C語法中有許多循環結構。它們是:

  • for()
  • while()
  • do/while()

無論這些應該是簡單的查找在任何參考材料您正在使用,並且既可以用它來解決這個問題。

+0

不要忘記'goto'&'setjmp()'! – 2012-01-16 20:45:38

+0

「'goto'&'setjmp()'」&遞歸...在C中,'main'可以遞歸地調用:) – pmg 2012-01-16 20:50:59

5

這看起來像是while循環和break聲明的好地方。您可以使用while循環這樣無限循環:

while (true) { 
    /* ... /* 
} 

然後,一旦某些條件爲真,並要停止循環,就可以使用break語句退出循環:

while (true) { 
    /* ... */ 

    if (condition) break; 

    /* ... */ 
} 

這樣,當用戶猜測正確時,您可以將break移出循環。

或者,你可以使用一個do ... while循環,其條件檢查循環是否應該退出:

bool isDone = false; 
do { 
    /* ... */ 

    if (condition) isDone = true; 

    /* ... */ 
} while (!isDone); 

希望這有助於!

+0

Downvoter-請您評論這個答案有什麼問題?如果可能的話,我很樂意改進它。 – templatetypedef 2012-01-16 20:52:47

+0

另請注意,使用'false' /'true'時'#include '。 – Gandaro 2012-01-16 20:57:09

+0

就像它變得乾淨一樣。 – theGrayFox 2013-08-02 23:41:35

1

試試這個:

printf("Please enter a value: "); 
do { 
    scanf("%i", &guess); 

    if (guess == value) { 
        printf("Congratulations, you guessed the right value"); 
    } 
    else if (guess > value) { 
        printf("That value is too high. Please guess again: "); 
    } 
    else if (guess < value) { 
        printf("That value is too low. Please guess again: "); 
} while (guess != value); 
0

你的預期計劃是

#include <stdio.h> 

void main (void) { 
    int value = 58; 
    int guess; 

    do 
    { 
     printf("please enter a value : "); 
     scanf("%i", &guess); 
     if(guess > value) 
      printf("this value is too big, "); 
     else if(guess < value) 
      printf("this value is too small, "); 
    }while(guess != value); 

    printf("Congradulation You Guessed The Right Number. \n"); 
} 
+0

@niklas你有沒有。 – Mohanraj 2012-04-24 05:16:48