猜数

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

#define MAX_NUMBER 100

void initialize_number_generator();
int new_secret_number();
void read_guesses(int secret_number);

main()
{
    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("A new number has been chosen. \n");
        read_guesses(secret_number);
        printf("Play again?  (Y/N) \n");
        
        // 特别注意,这里的 %c 前面要有空格。意思是跳过所有空格字符。
        scanf(" %c", &command);
        
        printf("\n\n");
    } while(command == 'y' || command == 'Y');
    
    return 0;
}


// initialize the random number generator using the time of day
void initialize_number_generator()
{
    srand((unsigned) time(NULL));
}

// return a randomly chosen number bewteen 1 and MAX_NUMBER
int new_secret_number()
{
    return rand() % MAX_NUMBER + 1;
}

/*  repeatedly reads user guess and tells the user 
*   whether each guess is too low,
*   too high, or correct. when the guess is correct,
*   prints the total number of guess and returns.
*/
void read_guesses(int secret_number)
{
    int guess, num_guesses = 0;
    
    for (;;)
    {
        num_guesses++;
        printf("Enter guess:");
        scanf("%d", &guess);
        
        if ( guess < 0 || guess > 100)
        {
            printf("You enter the illegal number. Game over ! \n");
            return ;
        }
        
        else 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");
    }
}

 

posted @ 2013-04-24 10:46  He_LiangLiang  阅读(289)  评论(1编辑  收藏  举报