Reading Stroustrup: Programming -- Principles and Practice Using C++, chapter 4, exercise 4:

"Write a program to play a numbers guessing game. The user thinks of a number between 1 and 100 and your program asks questions to figure out what the number is (e.g., "Is the number you are thinking of less than 50?"). Your program should be able to identify the number after asking no more than seven questions. Hint: Use < and <= opeartors and the if-else construct."

What I've managed so far, but what I have seems to be lacking

#include "../../std_lib_facilities.h"

int half(int guess);
int going_up(int i);

int main()
{
    int i = 100;
    i = half(i);
    i = going_up(i);
    i = half(i);
    i = going_up(i);
}

int going_up(int i)
{
    int temp = i;
    char answer = 'y';
    while (answer == 'y')
    {
        i = temp + (i / 2);
        cout << "Is the number you are thinking of more than " << i << " (y or n)? ";
        cin >> answer;
    }
    return i;
}

int half(int i)
{
    char answer = 'y';
    while (answer == 'y')
    {
        i /= 2;
        cout << "Is the number you are thinking of less than " << i << " (y or n)? ";
        cin >> answer;
    }
    return i;
}

Instead of modifying 1 value (i) to try and hit on the right answer, set lower and upper limits (1 and 100) then modify the limits to narrow the range until the correct answer is the only one left.

Read up about the Binary Chop algorithm.

@haulover. your code is interesting but somehow confusing to me. Wel am not an advance programmer. May be we could do some stuff together.

Your program should structure something like this:

int low=1;
int high=100;
while(low<high)
{
   int half=(low+high)/2;
   std::cout << "Is your number greather than " << half <<"? (Y/N): ";
   char answer;
   std::cin >> answer;
   if(answer == 'Y' || answer == 'y') low=half+1;
   else                               high=half;
}
std::cout << "\nYour number is: " << low << std::endl;

You should also add some control into the answer and thats it.

Edited 1 Year Ago by Maritimo

This article has been dead for over six months. Start a new discussion instead.