As an exercise, I'm trying to make a program where the computer tries to guess which number I am thinking of. I am able to make it give random guesses in general but I want to make it able to guess the right number more quickly by recording it's highest and lowest guesses and making new guesses in-between those.
For example, if the computer guesses 20 then 40, it's third guess should only be between 20 and 40. Is this possible and if so what am I doing wrong? #include #include #include using namespace std;
int main() { string yesOrNo; string lowOrHigh; srand(time(NULL)); int random_number = 1+(rand() % 100); int lowGuess(0); int highGuess(100); int guessAttempts(1); int adjustMinMax(int random_number, int& highestGuess, int& lowGuess, string lowOrHigh); int adjustGuess(int& random_number, int lowGuess, int highestGuess); cout << "Think of a random number between 1 and 100 in your head."; cout << endl << "Guesses Attempted: " << guessAttempts; cout << endl << "Is your number " << random_number << "?"; cout << endl << "y/n: "; cin >> yesOrNo; while (yesOrNo == "n" || yesOrNo == "no") { ++guessAttempts; cout << endl << "Was my guess too high or too low l/h? "; cin >> lowOrHigh; adjustMinMax(random_number, highGuess, lowGuess, lowOrHigh); adjustGuess(random_number, lowGuess, highGuess); cout << "Guesses Attempted: " << guessAttempts; cout << endl << "Is your number " << random_number << "?"; cout << endl << "y/n: "; cin >> yesOrNo; } cout << "Hooray! :)"; return 0; } int adjustGuess(int& random_number, int lowGuess, int highGuess) { random_number = rand() % (highGuess - lowGuess + 1) + lowGuess; return (random_number); } int adjustMinMax(int random_number, int& highGuess, int& lowGuess, string lowOrHigh) { if (lowOrHigh == "l" || lowOrHigh == "low") { return(lowGuess = random_number); } if (lowOrHigh == "h" || lowOrHigh == "high") { return(highGuess = random_number); } }
yesOrNo == 'no'should make the compiler shout warnings at you.