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 lower = 0;
int higher = 100;
int res = 0;
while (higher !=lower)
{
char answer[2]="";
std::cout << "Is your number bigger than " << (lower + higher) / 2 << "\nEnter y or n : ";
std::cin.getline(answer, 2);
if (answer[0] == 'y')
{
lower = (lower + higher) / 2+1;
}
else if (answer[0] == 'n')
{
higher = (lower + higher) / 2;
}
res = higher;
}
std::cout << "Your digit is :" << res << std::endl;
system("pause");
return 0;
}
Comments
Leave a comment