代码如下: 猜谜游戏,最多猜10次,提示用户重玩。运行一次后就崩溃了。如果没有 replay() 模块,它可以正常工作,但我无法合并重播选项。我尝试了几种不同的方法但无济于事。请及时帮助我解决这个问题。提前感谢您的帮助。 谢谢
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guessGame ();
int replay();
int main()
{
int selection;
printf("Welcome to the Number Guess Game! I choose a number between 1 and 100 and you\nhave only 10 chances to guess it!");
do
{
printf("\n\nok, I made my mind!");
guessGame();
replay();
}
while (replay() != 0);
printf("Thank you! have a nice day.\n");
return 0;
}
void guessGame()
{
int attempt,guess;
srand(time(NULL));
int r = rand () % 100 + 1;
for (guess = 1; (guess < 11 && attempt != r); guess = guess + 1)
{
printf("\nWhat is your guess> ");
scanf("%d",&attempt);
if (attempt < 1 || attempt > 100)
{
printf("Invalid guess!\n");
guess = guess - 1;
}
else
{
if (attempt > r && guess < 10)
printf("My number is smaller than %d\n",attempt);
else if (attempt < r && guess < 10)
printf("My number is larger than %d\n",attempt);
}
if ((guess < 9) && (attempt >= 1 && attempt <= 100))
printf("%d guesses left.\n",(10 - guess));
if ((guess == 9) &&(attempt >= 1 && attempt <= 100))
printf("%d guess left.\n",(10 - guess));
}
if (attempt == r)
{
printf("You did it! My number is %d.\nYou did it in %d guesses.\n",r,guess);
}
if (guess >= 10 && attempt != r)
{
printf("SORRY! you couldn't guess it with 10 guesses.\nMy number was %d. Maybe next time!\n",r);
}
}
int replay()
{
char selection;
printf("\nDo you want to play again");
scanf("%c",selection);
if (selection == 'N')
return 0;
else
return 1;
}
最佳答案
您错误地调用了 scanf()
。您需要给出要存储到的变量的地址:
scanf("%c", &selection);
关于c - 我的程序的代码只能运行一次并且不会循环 - 在代码块上出现错误并崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26812317/