C中的"猜1-1000游戏之间的数字".如何在不再次手动运行程序的情况下重播?



所以我有我的第一个C程序,你猜1到1000之间的数字。 它玩得足够好,但是当我按 Y 或 N 让用户在获胜后重玩游戏时,它只是结束了程序。 我想 n 杀死程序,y 重新重新启动它。 我该如何实现此目的? 这是程序。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int random_num = 0;
int guessed_num = 0;
int counter = 0;
char selection = 'y';
srand(time(NULL));
random_num = rand() % 1000 + 1;
printf("I have a number between 1 and 1000, can you guess my number??? ");
while (selection == 'y')
{
counter++;
scanf_s("%d", &guessed_num);
if (guessed_num == random_num)
{
printf("You guessed correctly in %d tries! Congratulations! Guess again? (y or n)n", counter);
scanf_s("%d", &selection);
break;
}
if (guessed_num < random_num)
printf("Your guess is too low. Guess again. ");
if (guessed_num > random_num)
printf("Your guess is too high. Guess again. ");
}
return 0;
}

您的程序正在等待用户的输入:

if (guessed_num == random_num)
{
printf("You guessed correctly in %d tries! Congratulations! Guess again? (y or n)n", counter);
scanf_s("%d", &selection);
break;
}

即使用户选择"是"或"否",根据您的逻辑,您使用"break"语句。 这打破了你的无限游戏循环,即使在输入"y"后你也会出来。 因此,请使用上一个答案中所说的解决方案。希望这能消除您的疑虑

把你的"玩一次游戏"逻辑放在一个更大的循环中,在玩游戏后,问"你想再玩一次吗?

char play_again = 'y';
while ( play_again == 'y' ) {
...
printf("do you want to play again?");
scanf_s("%c", &play_again);
}

在询问用户是否要再次玩游戏后,您将无条件地调用break。 无论他们选择什么,break都会突破while循环,退出你的程序。 只需摆脱break. 您也可以更改为else if...else条件,因为每次检查都是互斥的;例如,如果我们知道==是真的,检查<>是没有意义的。

if (guessed_num == random_num)
{
printf("You guessed correctly in %d tries! Congratulations! Guess again? (y or n)n", counter);
scanf_s("%d", &selection);
}
else if (guessed_num < random_num)
{
printf("Your guess is too low. Guess again. ");
}
else
{
printf("Your guess is too high. Guess again. ");
}