首页 > 解决方案 > 如何在范围检查之前重做代码以在循环顶部提示读取和输入

问题描述

我还是 C 程序的新手,但我正在学习。我收到了一些反馈,我不完全确定如何完成,并希望我希望这里的某个人能够解释一下。有人告诉我,将第一个猜测放在循环开始之前,将其与任何其他猜测区别对待并不是一个好主意。我应该对所有的猜测一视同仁。所以我应该在循环开始之前将guess初始化为0,并将代码提示并读取循环顶部的输入,以便在范围检查之前读取输入。我需要如何或在我的代码中更改什么来实现这一点?我相信我在顶部解决了将猜测初始化为 0 的问题,但我不确定其余部分是否正确。
谢谢你,安妮特

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

int main()
{

    int guess = 0;
    time_t t;
    int randNumber;
    int numberOfGuess;


    /*srand is used to seed the random number so that it is different every time.  This is giving the
    random number an initial base that the rand() can use to offset with a random number.*/
    srand(time(&t));

    /*This will initialize a random number between 0 and 20, but the +1 at the end adds a number so the
    created random number falls anywhere from 1 through 20*/
    randNumber = (rand()% 20) +1;

    /*Prompt the user to input a random number between 1 and 20 and increase the numberOfGuess counter
    by 1*/
    printf("Let's play a guessing game and see how many times it takes you to guess a preselected ");
    printf("random number between 1 - 20.\n");
    printf("Please guess a number between 1 and 20:\t");
    scanf("%d", &guess);

    /*This sets the while loop to validate if the guess is not the randNumber, which enables an escape once
    the guess is equal to the randNumber.*/
    while (guess != randNumber)
    {

        /*If the guess is lower than or equal to 0 or the guess is greater than 20, I print out the statement
        notifying the user and prompting the user to enter a new guess.  It is at this point that I also added
        a statement to increase the numberOfGuess count by 1 as this should be counted towards the guess total*/
        if (guess <= 0 || guess > 20)
        {
            printf("\nThe number guessed isn't between 1 and 20, please enter a new guess:  ");
            numberOfGuess++;
            scanf("%d", &guess);
        }

        /*If the guess in higher than the randNumber, I let the user know and ask the user to
        enter another guess and I added another statement to increase the numberOfGuess count
        by 1 as this should be counted towards the guess total*/
        else
        {
            if(guess > randNumber)
            {
                printf("\nYour guess of %d is too high, guess again:  ", guess);
                numberOfGuess++;
                scanf("%d", &guess);
            }

            /*If the guess in lower than the randNumber, I let the user know and ask the user to
            enter another guess and I added another statement to increase the numberOfGuess count
            by 1 as this should be counted towards the guess total*/

            else
            {
                if(guess < randNumber)
                {
                    printf("\nYour guess of %d is too low, guess again:  ", guess);
                    numberOfGuess++;
                    scanf("%d", &guess);
                }

            }
        }
    }

    /*The last item for this tasks prints the results with the correct guessed number, the number of guesses
     and the last statement to increase the numberOfGuess count by 1 as this should be counted towards the guess total.
     Also, this capture the count if the user's guess is correct the first time.  The while loop and if..else statements
     would not capture the count for a correct guess
     */
    numberOfGuess++;
    printf("\nYou guessed it, the number was %d and it took you %d guess(s)!", guess, numberOfGuess);

    return 0;
}

标签: c

解决方案


你可以这样做:

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

int main()
{
    int guess = 0;
    int randNumber;
    int numberOfGuess;
    const char * msg = "Please guess a number between 1 and 20:\t";

    /*srand is used to seed the random number so that it is different every time.  This is giving the
    random number an initial base that the rand() can use to offset with a random number.*/
    srand(time(NULL));

    /*This will initialize a random number between 0 and 20, but the +1 at the end adds a number so the
    created random number falls anywhere from 1 through 20*/
    randNumber = (rand()% 20) +1;

    /*Prompt the user to input a random number between 1 and 20 and increase the numberOfGuess counter
    by 1*/
    printf("Let's play a guessing game and see how many times it takes you to guess a preselected ");
    printf("random number between 1 - 20.\n");

    /*This sets the while loop to validate if the guess is not the randNumber, which enables an escape once
    the guess is equal to the randNumber.*/
    do
    {
        numberOfGuess += 1;
        printf(msg, guess);
        scanf("%d", &guess);

        /*If the guess is lower than or equal to 0 or the guess is greater than 20, I print out the statement
          notifying the user and prompting the user to enter a new guess.  It is at this point that I also added
          a statement to increase the numberOfGuess count by 1 as this should be counted towards the guess total*/
        if (guess <= 0 || guess > 20)
        {
            msg = "\nThe number guessed isn't between 1 and 20, please enter a new guess:  ";
        }

        /*If the guess in higher than the randNumber, I let the user know and ask the user to
          enter another guess and I added another statement to increase the numberOfGuess count
          by 1 as this should be counted towards the guess total*/
        else if(guess > randNumber)
        {
          msg = "\nYour guess of %d is too high, guess again:  ";
        }
             
        /*If the guess in lower than the randNumber, I let the user know and ask the user to
          enter another guess and I added another statement to increase the numberOfGuess count
          by 1 as this should be counted towards the guess total*/
        else if(guess < randNumber)
        {
          msg = "\nYour guess of %d is too low, guess again:  ";
        }
    } while (guess != randNumber);

    /*The last item for this tasks prints the results with the correct guessed number, the number of guesses
     and the last statement to increase the numberOfGuess count by 1 as this should be counted towards the guess total.
     Also, this capture the count if the user's guess is correct the first time.  The while loop and if..else statements
     would not capture the count for a correct guess
     */
    printf("\nYou guessed it, the number was %d and it took you %d guess(s)!\n",
           guess, numberOfGuess);

    return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
Let's play a guessing game and see how many times it takes you to guess a preselected random number between 1 - 20.
Please guess a number between 1 and 20: 10

Your guess of 10 is too low, guess again:  15

Your guess of 15 is too low, guess again:  17

You guessed it, the number was 17 and it took you 3 guess(s)!
pi@raspberrypi:/tmp $ 

我使用 ado while但当然您也可以执行 afor(;;)或等效操作,并在if ... else if ...串行中添加 finalelse break;以不检查猜测额外的时间(但可能编译器优化当前代码不这样做)

注意我在函数的参数中给出了NULLtime() ,因为我不需要保存当前时间。

正如你所看到的,我增加numberOfGuess并且scanf只调用一次,这很简单。printf循环中也只有一个,但有几个分配来设置正确的格式。

第一次printf(msg, guess);执行的格式不包含 a%d所以参数guess没有使用,这不是问题。

但是有一个很大的问题,如果用户没有输入一个有效的整数,程序没有结束就循环,需要检查结果scanf并绕过无效输入,例如刷新整行,例如替换:

scanf("%d", &guess);

/*If the guess is lower than or equal to 0 or the guess is greater than 20, I print out the statement
  notifying the user and prompting the user to enter a new guess.  It is at this point that I also added
  a statement to increase the numberOfGuess count by 1 as this should be counted towards the guess total*/
if (guess <= 0 || guess > 20)

经过 :

if (scanf("%d", &guess) != 1)
{
  /* invalid input, flush all the line */
  while ((guess = getchar()) != '\n')
  {
    if (guess == EOF)
    {
      puts("abort game");
      return 0;
    }
  }
  guess = 0; /* to not be the search value whatever \n encoding */
  msg = "\ninvalid input, it was not a number, please enter a new guess:  ";
}

/*If the guess is lower than or equal to 0 or the guess is greater than 20, I print out the statement
  notifying the user and prompting the user to enter a new guess.  It is at this point that I also added
  a statement to increase the numberOfGuess count by 1 as this should be counted towards the guess total*/
else if (guess <= 0 || guess > 20)

编译和执行:

pi@raspberrypi:/tmp $ ./a.out
Let's play a guessing game and see how many times it takes you to guess a preselected random number between 1 - 20.
Please guess a number between 1 and 20: qsd

invalid input, it was not a number, please enter a new guess:  qsd

invalid input, it was not a number, please enter a new guess:  1

Your guess of 1 is too low, guess again:  qsd

invalid input, it was not a number, please enter a new guess:  ^C
pi@raspberrypi:/tmp $ 

当你读到一个值时,我鼓励你永远不要认为它是有效的,并且总是检查它是否有效。


推荐阅读