c - 我的程序的代码只能运行一次并且不会循环 - 在代码块上出现错误并崩溃

标签 c

代码如下: 猜谜游戏,最多猜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/

相关文章:

C编程指针char数组

c - 在 C 中获取 Windows 串行端口的输入缓冲区长度

c - gethostbyname,连接到整个互联网?

C 标识符限制

c - 减少循环中的内存访问 (C)

c - 如何在 Visual Studio 2012 中创建 ANSI C 文件?

c - 无限循环的原因

客户端通过套接字与服务器进行通信

c - 如何在不使用 SIGWAIT 的情况下阻止线程中的所有信号?

c++ - pthread_mutex_lock 阻塞但 __lock = 0