C++ random number generator questions

I'm making a random number guessing game and I'm done with most of the body of the coding but I'm unsure of what is wrong with the main srand and rand parts. In the game I prompt the user to choose the range they want the game to be in, in userMinRand as minimum and userMaxRand as maximum.

1
2
3
4
		int number, userMaxRand, userMinRand, xGuess;

		srand(time(NULL));
		number = rand() % userMaxRand + userMinRand;


Everything except this works fine but this is the most important part, no matter what range the user choose, the initialization of the integer number is always this giant 6 digit number and not random what so ever.
You never initialize your variables. It's a garbage value. You never give userMaxRand and userMindRand a value, so how is it suppose to know what range you want?

Edit:

to add to @DDomjosa, watch this video - https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
Last edited on
Try this:

1
2
3
std::random_device randomGenerator;
std::uniform_int_distribution<int> randomNumber(userMinRand, userMaxRand);
number = randomNumber(randomGenerator);


Don't forget to write #include <random> .
I am presuming (perhaps I shouldn't) that somewhere between line1 and line 4, some initial values are assigned to userMaxRand and userMinRand.

The number of possible values is (userMaxRand - userMinRand + 1)
Hence you should use rand() % (userMaxRand - userMinRand + 1) and then add userMinRand.

A couple of other comments. You should call srand() only once, at the start of the program, not each time you want to generate a random number. Another comment, after that initialisation, the first couple of values generated by rand() may not be very random, so you may want to just call rand() a few times and ignore the result in order to get it started.
The values assigned to userMinRand and userMaxRand are user assigned but before the user inputs a value to each they aren't initialized, whenever i initialize them to 0 it says DivideByZero error or another number messes it up even more.
whenever i initialize them to 0 it says DivideByZero error


Well, if you do this:
number = rand() % userMaxRand + userMinRand;
and replace the variables by zero, you get this:
number = rand() % 0 + 0;

This will indeed give a divide by zero error.

rand() % 0

The values assigned to userMinRand and userMaxRand are user assigned
- but does the user enter these values before you try to use them? It sounds as though you have some instructions out of sequence.
e.g.
calculate the answer first
then find out what was the question.
Last edited on
Topic archived. No new replies allowed.