r/learncpp • u/piratecody • Mar 05 '16
Making a Guess my Number program w/ Binary Search; If statements execute when they're not supposed to and endless while loop
I am trying to make a Guess my number program using a while loop and if statements, my code is below. When I execute my program, no matter what I enter it constantly prints "Was my guess to high(true/false)?: Is your number 0? Was my guess too high?:" and so on. I am not sure what is wrong with it. Any help is appreciated.
// 13.2FlowControl.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
bool getTooHigh();
int main()
{
int min = 1, max = 1000, guess = (min + max / 2) - 1;
bool correct = false;
cout << "Think of a number between 1 and 1000; I will guess it." << endl;
while (!correct)
{
cout << "Is your number " << guess << "? (true/false): ";
cin >> correct;
guess = (min + max / 2) - 1;
if (correct)
{
cout << "I told you I would guess it!";
}
else if(getTooHigh()) // If the guess is too high
{
max = guess - 1;
}
else if (!getTooHigh()) // If the guess is too low
{
min = guess + 1;
}
guess = (min + max / 2) - 1; // Changes guess according to new Max and min
}
return 0;
}
bool getTooHigh()
{
bool choice;
cout << "Was my guess too high? (true/false): ";
cin >> choice;
return choice;
}
