/********************************************************
* guess -- a simple guessing game *
* *
* Usage: *
* guess *
* *
* A random number is chosen between 1 and 100. *
* The player is given a set of bounds and *
* must choose a number between them. *
* If the player chooses the correct number he wins*
* Otherwise the bounds are adjusted to reflect *
* the player's guess and the game continues. *
* *
* *
* Restrictions: *
* The random number is generated by the statement *
* rand() % 100. Because rand() returns a number *
* 0 <= rand() <= maxint this slightly favors *
* the lower numbers. *
********************************************************/
#include <stdio.h>
#include <stdlib.h> /* ANSI Standard only */
int number_to_guess; /* random number to be guessed */
int low_limit; /* current lower limit of player's range */
int high_limit; /* current upper limit of player's range */
int guess_count; /* number of times player guessed */
int player_number; /* number gotten from the player */
char line[80]; /* input buffer for a single line */
main()
{
while (1) {
/*
* Not a pure random number, see restrictions
*/
number_to_guess = rand() % 100 + 1;
/* Initialize variables for loop */
low_limit = 0;
high_limit = 100;
guess_count = 0;
while (1) {
/* tell user what the bounds are and get his guess */
(void) printf("Bounds %d - %d\n", low_limit, high_limit);
(void) printf("Value[%d]? ", guess_count);
guess_count++;
(void) fgets(line, sizeof(line), stdin);
(void) sscanf(line, "%d", &player_number);
/* did he guess right? */
if (player_number == number_to_guess)
break;
/* adjust bounds for next guess */
if (player_number < number_to_guess)
low_limit = player_number;
else
high_limit = player_number;
}
(void) printf("Bingo\n");
}
return (0);
}
syntax highlighted by Code2HTML, v. 0.9.1