簡體   English   中英

猜游戲程序

[英]Guessing Game Program

我創建了一個簡單的猜謎游戲程序。 我的問題是,一旦用戶猜錯了數字,我不確定如何將程序循環回到程序的開頭。 我希望程序繼續向用戶詢問一個數字,直到他正確為止。 有人能幫我嗎?

#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;
}

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

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

然后,一旦某些條件變為真並且您想要停止循環,則可以使用break語句退出循環:

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

     if (condition) break;

     /* ... */
}

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

另外,您可以使用do ... while循環,其條件檢查循環是否應該退出:

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

    if (condition) isDone = true;

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

希望這可以幫助!

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

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

使用您所使用的參考資料中的任何一種都應該很容易查找,並且可以使用其中任何一種來解決此問題。

嘗試這個:

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);

您期望的程序是

#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");
}

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

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

當然,應該在人們輸入Y而不是y的情況下進行修復,但要點是,您需要將程序包裝在do while循環中(它將至少執行一次)或while循環(在輸入之前獲取初始值)條件)以及初始啟動條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM