猜数游戏1.0

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了猜数游戏1.0相关的知识,希望对你有一定的参考价值。

程序产生一个1-100的随机数,用户尝试尽可能少的次数猜出这个数。

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

#define MAX_NUMBER 100

//external variable
int secret_number;

//prototypes
void initialize_number_generator(void);
void choose_new_secret_number(void);
void read_guesses(void);

int main(void)
{
    char command;

    printf("Guess the secret number between 1 and %d.\n\n", MAX_NUMBER);
    initialize_number_generator();
    do {
        choose_new_secret_number();
        printf("Anew number has been chosen.\n");
        read_guesses();
        printf("Play again? (Y/S) ");
        scanf(" %c", &command);
        printf("\n");
    } while (command == y || command == Y);

    return 0;
}

//initialize_number_generator:Initialize the random number generator using the time of day.

void initialize_number_generator(void)
{
    srand((unsigned)time(NULL));
}

//choose_new_secret_number:Randomly selects a number between 1 and MAX_NUMBER and stores it in secret_number.

void choose_new_secret_number(void)
{
    secret_number = rand() % MAX_NUMBER + 1;
}

//read_guesses:Repeatedly reads user guesses and tells the user whether each guess is too low, too high, or correct. When the guess is correct, prints the total number of guesses and returns.

void read_guesses(void)
{
    int guess, num_guesses = 0;

    for (;;) {
        num_guesses++;
        printf("Enter guess: ");
        scanf("%d", &guess);
        if (guess == secret_number) {
            printf("You won in %d guesses!\n\n", num_guesses);
            return;
        }
        else if (guess < secret_number)
            printf("Too low, try again.\n");
        else
            printf("Too high, try again.\n");
    }
}

 

以上是关于猜数游戏1.0的主要内容,如果未能解决你的问题,请参考以下文章

猜数小游戏升级版(IO流实现,对IO流进行加强理解运用)

猜数小游戏代码实现

rust猜数游戏代码

c语言猜数游戏编程

随机猜数游戏源代码

猜数小游戏