程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 猜數游戲2.0,猜數2.0

猜數游戲2.0,猜數2.0

編輯:關於C語言

猜數游戲2.0,猜數2.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);
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");
    }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved