簡體   English   中英

C中子手程序的麻煩

[英]trouble in hangman program in c

在for循環中,以及在if語句中,由於某種原因,即使它們彼此相反,它也會通過兩個if語句,而且我不知道為什么這樣做。 我嘗試了不同的方法,但結果仍然相同。

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



int main ()
{
char secretword[20] = {};
char alphabet[28] = {"abcdefghijklmnopqrstuvwxyz "};
char guess[2] = {};
int i = 0, k = 0;
int seclength = 0, alphlength = 0;
int GuessCtr = 6;

printf("You Get six chances to guess all of the letters in a phrase\n");
printf("Enter the secret word/phrase: ");
scanf("%s", &secretword);
seclength = strlen(secretword);
alphlength = strlen(alphabet);
while(GuessCtr != 0)
{
    printf("Past guesses: ");
    for(i = 0; i < alphlength; i++)
    {
        printf("%c", alphabet[i]);
    }
    printf("\n");
    printf("Guess a character: ");
    scanf("%s", &guess);
    printf("\n");
    for(i = 0; i < seclength; i++)
    {
            if(secretword[i] == guess[0])
            {
                secretword[i] = '*';
            }
            /*else
            {
                GuessCtr--;
                printf("You missed - you have %d wrong guesses left!", GuessCtr);
            }*/
            if(secretword[i] != guess[0])
            {
                GuessCtr--;
                printf("You missed - you have %d wrong guesses left!", GuessCtr);
            }
    }

    for(i = 0; i < seclength; i++)
    {
        printf("%c", secretword[i]);
    }
    printf("\n");
    for(i = 0; i < alphlength; i++)
    {
        if(alphabet[i] == guess[0])
        {
            alphabet[i] = '*';
        }
    }
}
printf("You suck!");


return 0;

}

因為第一個if語句的主體更改了它測試的變量,第二個if語句的主體將再次測試。 當計算第二個if ,該變量的值與第一次不同。

要解決此問題,您需要使用else ,因此從第一時間起就“記住”該條件:

        if(secretword[i] == guess[0])
        {
            secretword[i] = '*';
        }
        else
        {
            GuessCtr--;
            printf("You missed - you have %d wrong guesses left!", GuessCtr);
        }

我懷疑您被該程序出了什么問題誤導了。

由於這似乎是一項家庭作業,因此我不會回答總體情況,但是您應該仔細檢查以下語句以查找錯誤:

scanf("%s", &secretword);

暫無
暫無

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

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