gpt4 book ai didi

c - C中的循环猜谜游戏

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

让用户猜测程序选择的幸运数字的程序。它使用一个 for 循环和大量的 if 语句。问题是我的代码在 2 次尝试后停止,但假设给用户 3 次尝试。这是我目前所拥有的:

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

int main()
{
int iSecret, iGuess;
srand(time(NULL));
iSecret = rand() % 20 + 1;
int tries = 0;

printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");

for (tries = 0; tries < 3 || iSecret == iGuess; tries++)
{
printf("Please, enter a number between 1 and 20! ");
scanf("%d", &iGuess);

if (iGuess == iSecret)
{
printf("\nCongratulations! You won!");
return 0;
}

else if (iGuess > iSecret)
{
tries++;
printf("\nYour guess was too high.\n");
}

else if (iGuess < iSecret)
{
tries++;
printf("\nYour guess was too low.\n");
}
if (tries == 3)
break;
}

printf("\nYou have reached your third trials. The correct number is %d.\n",
iSecret);
return 0;
}

最佳答案

您正在递增 tries 两次:一次是在 for 定义中,另一次是在循环体中。

删除多余的 tries++ 语句。

关于c - C中的循环猜谜游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19508530/

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