Robson » Little Red Book » Guessing game

Chapter 6 - Question 15

Program the computer to ask a user to, "think of a three-digit number". Using the response "Y"and "N" to the question, "Is your number bigger than n" (where n is computed by the program), find the user's three-digit number.

Solution 1

PHP isn't a logical language to use when asking for user input multiple times, so I've written this solution in c++.

// this handles input and output
#include <iostream.h>
int main ()
   // the guess is the amount the user will be asked
   // the code can handle any min/max values if they're valid
   int iGuess, iMin = 111, iMax = 999;
   // the users response should be 1 if true and 0 if false
   int iResponse;
   // tell the user to think of a three digit number
   cout << "Think of a three digit number.\n" << "...\n";
   // only loop while the min and max values are different
   // which means we are still guessing
   while (iMin!=iMax)
       // guess half way between the min and max values
       // this will find the answer in the smallest number of questions
       iGuess = (iMin+iMax)/2;
       // ask the user
       cout << "Is your number bigger than " << iGuess << "?\n>";
       // get their response
       cin >> iResponse;
       // if they answered that the number is bigger
       if (iResponse == 1)
           // we know the minimum is the amount plus one
           iMin = iGuess+1;
           // it must be lower, so set the max to the guess
           iMax = iGuess;
       // when the min and max are the same, their can only be one answer
       if (iMin == iMax)
           // let the user know we found their number
           cout << "You were thinking of " << iMin << "!";
   return 0;

Which produces:

Guessing game


© 2004-17 robson | cc unless stated