gpt4 book ai didi

c - c中的刽子手程序的麻烦

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:06 24 4
gpt4 key购买 nike

在 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 时,变量的值与第一次不同。

要解决此问题,您需要使用 else,因此从第一次开始“记住”条件:

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

关于c - c中的刽子手程序的麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9728877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com