Write a program to play a number-guessing game with a human player. The player will think of a number, and the computer will try to guess it. After each guess, the human should tell the computer whether the guess was too high or too low. Eventually, the human will tell the computer it is correct and the game will end.
Here's how the computer should guess: start with three variables. Let's say they're called hi
, lo
, and guess
. At first, set lo
to 1 and hi
to 1000, since that's the range.
You should make guess
equal to the average of lo
and hi
, since that's halfway. That is, set guess
equal to ( lo + hi ) / 2
.
Then, if the computer finds out that its guess was too high, you should make hi
equal to guess
. For example, if the computer guesses 500 and that's too high, then the computer should now guess in the range 1-500, so lo
should still be 1 but hi
should now be 500 instead of 1000.
Similarly, if the guess ends up being too low, then your program should change the value of lo
to the last guess
. For example, if the computer guesses 500 and that's too low, then the computer should now guess in the range 500-1000.
You'll need to use a while
loop that keeps going as long as the human's answer isn't 'c'
.
Think of a number from 1 to 1000. I'll try to guess it.
My guess is 500. Am I too (h)igh, too (l)ow, or (c)orrect?
> h
My guess is 250. Am I too (h)igh, too (l)ow, or (c)orrect?
> h
My guess is 125. Am I too (h)igh, too (l)ow, or (c)orrect?
> l
My guess is 187. Am I too (h)igh, too (l)ow, or (c)orrect?
> h
My guess is 156. Am I too (h)igh, too (l)ow, or (c)orrect?
> h
My guess is 140. Am I too (h)igh, too (l)ow, or (c)orrect?
> h
My guess is 132. Am I too (h)igh, too (l)ow, or (c)orrect?
> l
My guess is 136. Am I too (h)igh, too (l)ow, or (c)orrect?
> h
My guess is 134. Am I too (h)igh, too (l)ow, or (c)orrect?
> h
My guess is 133. Am I too (h)igh, too (l)ow, or (c)orrect?
> c
Ha! I am the greatest guesser in the WORLD!
©2017 Graham Mitchell