Number of game guesses: 2.0; number of guesses: 2.0

Source: Internet
Author: User

Number of game guesses: 2.0; number of guesses: 2.0

The program generates a random number ranging from 1 to. The user tries to guess the number as few times as possible.

#include<stdio.h>#include<stdlib.h>#include<time.h>#define MAX_NUMBER 100//external variableint secret_number;//prototypesvoid initialize_number_generator(void);int new_secret_number(void);void read_guesses(void);int main(void){    char command;    int secret_number;    printf("Guess the secret number between 1 and %d.\n\n", MAX_NUMBER);    initialize_number_generator();    do {        secret_number = new_secret_number();        printf("Anew number has been chosen.\n");        read_guesses(secret_number);        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));}//Returns a randomly chosen number between 1 and MAX_NUMBER.int new_secret_number(void){    return 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(int secret_number){    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");    }}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.