From 7e0f021a9aec35fd8e6725e87e3313b101d26f5e Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Sun, 27 Jan 2008 11:37:44 +0100 Subject: Initial import (2.0.2-6) --- reference/C/CONTRIB/OR_PRACTICAL_C/06_3.c | 66 +++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 reference/C/CONTRIB/OR_PRACTICAL_C/06_3.c (limited to 'reference/C/CONTRIB/OR_PRACTICAL_C/06_3.c') diff --git a/reference/C/CONTRIB/OR_PRACTICAL_C/06_3.c b/reference/C/CONTRIB/OR_PRACTICAL_C/06_3.c new file mode 100644 index 0000000..bc0598a --- /dev/null +++ b/reference/C/CONTRIB/OR_PRACTICAL_C/06_3.c @@ -0,0 +1,66 @@ +/******************************************************** + * 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 +#include /* 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); +} -- cgit v1.2.3-54-g00ecf