Create a program that asks the user a series of questions that begin, “Is your number bigger than…” in order to deduce what integer between 1 and 100 they are thinking of. The user should only be able to answer ‘y’ or ‘n’ to each question. (Hint: each time round the loop, you should be seeking to halve the range in which number could lie, so store an upper bound and a lower bound, and change one or the other according to the user’s answers).
#include <iostream>
int main()
{
int number = 0;
char answer = 'n';
int lower_border = 0;
int high_border = 0;
std::cout << "Imagine a number between 0 and 10000" << std::endl;
std::cin >> number;
while(true)
{
int middle = (lower_border + high_border) / 2 ;
std::cout<<"Is your number bigger than middle?"<<std::endl;
std::cin>>answer;
if(answer == 'y')
{
lower_border = middle;
}
else
{
high_border = middle;
}
}
}
Comments
Leave a comment