两个问题,为什么双重打印以及如何重新开始! C编程

Two questions, why the double print and how to start it over again! C programming

我正在用 C 编写最简单的游戏 - 猜数字游戏。游戏本身运行良好。耶我。问题是我不知道如何重新开始。请参阅下面的代码:

  int main()
{
    int number, innum, times = 0;
    char playAgain;
    srand((unsigned)time(NULL));
    number = 5;//rand() % 1000;
for(;;)
{
    while(innum != number)
    {

        printf("Enter a number: ");
        scanf("%d", &innum);

        if(innum > number)
            printf("The entered number is too big!\n");
        if(innum < number)
            printf("The entered number is too small!\n");

        times++;

        if(innum == number)
        {
            printf("Congrats you guessed right!\n");
            printf("It took you %d tries\n", times);
        }

    }

    printf("Do you want to play again?");
    scanf("%c", &playAgain);
    if(playAgain == 'n')
        break;


}
return 0;
}

第一个问题是它打印了两次"Do you want to play again?"。这是为什么?另一个问题是,如何让游戏重新开始?

提前致谢。

这应该适合你:

(我做了什么?通过 scanf 添加了一个 space 并将 numbertimesinnum 的声明放在 for 循环中)

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

int main() {

    int number, innum, times;
    char playAgain;
    srand((unsigned)time(NULL));

    for(;;) {

        /*Declare the variables here*/
        number = 5; //rand() % 1000;
        innum = 0;
        times = 0;

        while(innum != number) {

            printf("Enter a number: ");
            scanf("%d", &innum);

            if(innum > number)
                printf("The entered number is too big!\n");
            if(innum < number)
                printf("The entered number is too small!\n");

            times++;

            if(innum == number) {
                printf("Congrats you guessed right!\n");
                printf("It took you %d tries\n", times);
            }

        }

        printf("Do you want to play again?");
        scanf(" %c", &playAgain);
             //^Added space here to 'eat' any new line in the buffer
        if(playAgain == 'n')
            break;


    }

    return 0;

}

可能的输出:

Enter a number: 2
The entered number is too small!
Enter a number: 6
The entered number is too big!
Enter a number: 5
Congrats you guessed right!
It took you 3 tries
Do you want to play again?y
Enter a number: 3
The entered number is too small!
Enter a number: 5
Congrats you guessed right!
It took you 2 tries
Do you want to play again?n