一个程序,让用户猜测程序选择作为幸运数字的数字。它使用一个 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;
}