I am currently working through Beginning C++ Through Game Programming 3rd Edition, just to help brush up on my C++. I've only been through one C++ book once and it took me quite a while to understand it properly, but going through this so far is helping my quite a lot. I used to have trouble creating programs because I didn't know how to implement certain ideas into code.
I'm only on Chapter 2, I've got a random number game up and running. Basically, the book asks you to rewrite a program which asks the user to guess a random number by the compiler.
I set up a range for the random number which is between 1 and 100:
int minNumber = 1;
int maxNumber = 100;
int compsNumber = (rand() % maxNumber) + minNumber;
So it should create a random number between 1 and 100. The user enters a number and then a random number should be generated. It will enter a while loop and test the computers numbers to the users number:
if(compsNumber < myNumber)
{
...
minNumber = compsNumber + 1;
}
else if(compsNumber > myNumber)
{
...
maxNumber = compsNumber - 1;
}
So if the random number is less than the users number, it will tell the computer it is too low and set the minimum number (1) to the computers current number plus 1 (so any number below the previous guessed number and the guessed number doesn't show up again). If the computers number is too high, set the maximum number (100) to the computers current number minus 1 (so any number higher than the previous guessed number and the guessed number doesn't show up again).
It will keep looping through, displaying the guessed number, until the computers number matches the users number. At the end of the loop, I generate a new random number between the new range based on the new minimum and maximum ranges:
compsNumber = rand() % maxNumber + minNumber;
The problem I am having is that it's also generating a number above the maximum number which it shouldn't do. Depending on how big my number will determine how big the random number is, so it will sometimes go into the 300's. Am I generating a random number wrong or something??
I am seeding the random number generator like so:
srand(static_cast<unsigned int>(time(0));