The assignment is to write a program that will correctly guess a generated number between 1 and 100. My program can correctly guess any number between 1 and 99. If the generated number is 100, then my program gets stuck in an infinite loop, with the number_guesser function continuously outputting the number 99. I attempted to adjust the output value upward, but then my program will correctly guess a generated number between 2 and 100 but get stuck in an infinite loop if the generated number is 1.
Although I suppose I could use if statements to negotiate boundary values, I believe there must be a better solution. Suggestions?
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <random>
#include <string>
usingnamespace std;
int number_guesser( int min, int max );
int number_generator( int min, int max );
int main ()
{
int min = 1;
int max = 100;
int generated_number = number_generator(min, max);
int guessed_number;
int count = 0;
bool correct_guess = false;
cout << "This program picks a number between ";
cout << min << " and " << max;
cout << " and lets the user try to guess the chosen number.\n";
while ( !correct_guess )
{
cout << "Please enter a number: ";
guessed_number = number_guesser(min, max);
++count;
if ( guessed_number == generated_number )
{
cout << guessed_number << " is correct!\n";
correct_guess = true;
}
elseif ( guessed_number < generated_number )
{
cout << "Too low. Please try again.\n";
min = guessed_number;
}
elseif ( guessed_number > generated_number )
{
cout << "Too high. Please try again.\n";
max = guessed_number;
}
}
cout << "You took " << count << " guesses.\n";
return 0;
}
int number_generator( int min, int max )
{
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> distrib(min, max);
return distrib(gen);
}
int number_guesser( int min, int max )
{
int output = ( max - min ) / 2 + min;
cout << output << '\n';
return output;
}
Your number_guesser function isn't necessarily wrong. I think the place to improve is when you assign the new min and max values in the loop.
Lines 37 and 40: The guessed number is lower than the actual number, but you're letting the min number be the same guessed number again.
Same idea for lines 42 and 45, but max is being assigned to be the same thing.
e.g. You guessed 99 and it says 99 is too low. Well then, it must be 99 + 1.
This should generally improve your guessing count overall.
Small point but if number_generator() was called multiple times (say in a loop), then you'd make rd, gen and distrib static so that they were only initialised once.
Also,
L56 and 57 can be combined:
std::mt19937 gen(std::random_device {}());
L17 generated_number could be marked const as it's value doesn't change.
L18. This isn't needed. L29 can define and initialise guessed_number.
L20 can be removed and L26 turned into a for loop