Hey guys, I'm just a newbie code writer..
I'm playing with a guessing game program as a personal exercise, but I'm missing a vital piece - the binary search-style code. I was wondering if you guys could help me solve this!
"Have the program initially guess 50, and have it ask the user whether the guess is high, low, or correct. If, say, the guess is low, have the next guess be halfway between 50 and 100, that is, 75. If that guess is high, let the next guess be halfway between 75 and 50, and so on." (We're assuming that the user won't cheat.)
I need the average, essentially. As in, (50 + 75) / 2 = 63.. but when I use this method of "guess = (high+low)/2, it just keeps giving me 50.
I can't remember what operators I should use to increment the program's response based on the user's input, and can't find help anywhere - which is making me crazy for a solution. It's literally a binary search, that needs to go where those TODOs are. If low was chosen, it would have to start by being at least 51, to 100, so I'd have to set that, then find the average.
Does anyone know of an efficient way to set this up? If I don't find an answer I'll drive myself crazy haha
Code:
#include <ctype.h>
int main(int argc, const char * argv[])
{
int low;
int high;
int guess;
int response;
int toupper ( int );
do
{
low = 1;
high = 100;
guess = 50;
printf("Pick an integer from 1 to 100 and I will try to guess it.\n");
printf("If I guess too low, respond with a L.\n");
printf("If I guess too high, respond with a H.\n");
printf("If I guess correctly, respond with a Y.\n");
printf("Okay, is your number %d?\n",guess);
while( (response=getchar()) != 'y')
{
if( response == 'l' )
{
// TODO: Ajust the value of low
// TODO: Ajust the value of guess
printf("Too low eh...well then, is it %d?\n",guess);
}
else if( response == 'h' )
{
// TODO: Ajust the value of high
// TODO: Ajust the value of guess
printf("Too high eh...well then, is it %d?\n",guess);
}
else if( response != '\n' )
{
fflush(stdin);
printf("Sorry, I only understand L, H and Y. Please try again.\n");
}
}
printf("Please enter R to restart, or Q to quit.\n");
response=getchar();
while ((response != 'q') && (response != 'r'))
{
if (response != '\n')
{
fflush(stdin);
printf("Oops! Please enter R or Q.\n");
}
response=toupper(getchar());
}
} while (response=='R');
return 0; }