The question asks to allow the user to input a certain number then count the number of guesses it would take for the program to guess the number. Initial must be 0 and final is 10,000. I am asked to first guess the number in the middle of the range. If the number inputted is higher than the midpoint, I must consider the higher half part of the range which is 5000 to 10,000, and so on.
Examples stated:
input guesses
2500 2
1225 11
8750 3
30 10
For some reason, I can't get it to work. This is what I have so far:
# include <iostream>
using namespace std;
int main(){
int init=0, fin=10000,num, guess=0, cntr=0;
cout<<"Insert target numbers:"<<endl;
cin>>num;
int range, midpoint;
range = (fin-init)/2;
while (!(fin-init==0))
{
midpoint = init + range;
Your variables init and fin are sort of like lower and upper or left-picket and right-picket. You are trying to simply corral in a baby calf into a little fenced in area, and we do it without knowing anything more than greater or lesser, and by moving the pickets of the fence closer and closer. Eventually, the baby calf has no choice but to either run away or get with his buddies inside.
So the line if(num > midpoint) init = midpoint + 1 should be changed to read:
// Assume cntr initialized to 1.
// while loop
if(num == midpoint) break; // Found num, finished.
else if(num > midpoint) init = midpoint; // Move the left picket.
else
fin = midpoint; // Move the right picket (since num < midpoint).
cntr++;
// Update midpoint each execution of the loop:
midpoint = (fin + init)/2;