blob: bc0598a45a1903d28438a1e1d027ccb388c69a94 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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 <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);
}
|