Saya masih baru dalam program C, tetapi saya sedang belajar. Saya menerima beberapa umpan balik yang saya tidak sepenuhnya yakin bagaimana mencapainya dan saya berharap bahwa saya berharap seseorang di sini mungkin dapat menjelaskannya. Saya diberitahu bahwa bukanlah ide yang baik untuk memperlakukan tebakan pertama secara berbeda dari tebakan lainnya dengan meletakkannya sebelum awal perulangan. Saya harus memperlakukan semua tebakan dengan sama. Jadi saya harus menginisialisasi tebak ke 0 sebelum memulai loop dan meletakkan kode untuk meminta dan membaca input di bagian atas loop sehingga input dibaca sebelum pemeriksaan rentang. Bagaimana atau apa yang perlu saya ubah dalam kode saya untuk mencapai ini? Saya yakin saya membahas inisialisasi tebakan ke 0 tepat di atas, tetapi saya tidak yakin tentang sisanya atau itu benar.
Terima kasih, Annette

#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
1
Annette Kitz 1 Juli 2020, 17:35

1 menjawab

Jawaban Terbaik

Kamu bisa melakukannya :

#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;
}

Kompilasi dan eksekusi:

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 $ 

Saya menggunakan do while tetapi tentu saja Anda juga dapat melakukan for(;;) atau yang setara dan dalam serial if ... else if ... tambahkan else break; final untuk tidak mencentang tebak waktu tambahan (tetapi mungkin kompiler mengoptimalkan kode saat ini untuk tidak melakukannya)

Catatan Saya memberikan NULL dalam argumen ke fungsi time() karena saya tidak perlu menghemat waktu saat ini.

Seperti yang Anda lihat, saya menaikkan numberOfGuess dan memanggil scanf hanya satu kali, itu menyederhanakan. Ada juga hanya satu printf dalam loop tetapi beberapa tugas untuk mengatur format yang tepat.

Pertama kali printf(msg, guess); dijalankan, format tidak mengandung %d sehingga argumen tebak tidak digunakan, ini bukan masalah.

Tetapi ada masalah besar, jika pengguna tidak memasukkan bilangan bulat yang valid, program berulang tanpa akhir, diperlukan untuk memeriksa hasil scanf dan melewati input yang tidak valid misalnya mem-flush baris penuh, jadi misalnya menggantikan:

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)

Oleh :

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)

Kompilasi dan eksekusi:

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 $ 

Saat Anda membaca sebuah nilai, saya mendorong Anda untuk tidak pernah menganggapnya valid dan selalu memeriksanya.

0
bruno 1 Juli 2020, 15:39