gpt4 book ai didi

c - "Guess The Number"在 C 语言中但 If 语句不能正常工作

转载 作者:行者123 更新时间:2023-11-30 19:07:40 26 4
gpt4 key购买 nike

我有一个 C 语言程序,用户运行它来玩“猜数字”游戏。它启动时运行正常,但在用户输入 2 个数字(1 个用于初始,1 个用于重试)后,程序会在尝试次数有限时重复。

这是我的程序代码:

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

int main(void)
{
//----Guess a Number Game.-----------------------------------------
// srand and rand needs the #include <stdlib.h> library

srand(time(NULL)); //seeding the guess a number game with the system time, so the guess a # game always starts at a different point.
int guess;
int correctnum;
correctnum = rand();

printf("Enter a number:");
scanf("%i",&guess);

if(guess>correctnum) // If aa is greater than bb AND aa is greater than cc.
{
printf("Please enter another number, lower this time!");
scanf("%i",&guess);
main();
}

else if (guess<correctnum)
{
printf("Please enter another number, higher this time!");
scanf("%i",&guess);
main();
}

else if (guess==correctnum)
{
printf("You are a WINNER!\n");
printf("You guessed the number right and it was %i!\n",correctnum);
}
int repeat;
printf("Would you like to play again? 1=Yes and 2=No.");
scanf("%i",&repeat);

if(repeat==1)
{
main();
}
if(repeat==2)
{
printf("Hope you had a good time playing the game! See you soon!\n");
return 0;
}
}

最佳答案

不要递归调用main()。您需要的是一个简单的循环。像这样的东西:

int main(void) {
srand(time(NULL));
int correctnum = rand();
int guess;
int done = 0;

while (! done) {
printf("Enter a number:");
scanf("%i",&guess);

if (guess>correctnum) {
printf("Please enter another number, lower this time!");
} else if (guess<correctnum) {
printf("Please enter another number, higher this time!");
} else /* if (guess==correctnum) */ {
printf("You are a WINNER!\n");
printf("You guessed the number right and it was %i!\n",correctnum);

done = 1;
}
}
}

您可能也应该检查 scanf() 中的错误,但首先要注意的事情。

关于c - "Guess The Number"在 C 语言中但 If 语句不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535359/

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