### Random number generator isn't working???

I am using the directive "#include <ctime>" and I have the following set up:

seed = time(0);
srand(seed);

Thing is, it works fine when I use the simple assignment such as:

`number = 0 + rand() % 100;`

but it goes haywire when I try to add a different minimum or maximum number, like:

`number = 85 + rand() % 115;`

It's generating numbers far beyond the supposed maximum that is supposed to be 115 and it only increases as I run it more

What is going on an how do I fix this? Would appreciate some help

This is my current full code:

 ``123456789101112131415161718192021`` ``````#include #include #include using namespace std; int main() { int number; unsigned seed; seed = time(0); srand(seed); number = 85 + rand() % 115; cout<
Do you understand how the % operator works?
Hmm. All I know is that it gives the remainder of an operation. On other sites I checked their methods of doing this and it involved doing the same thing with rand() then adding a number that was to be the minimum...
And do you understand operator precedence?
`rand()` returns a random number in the range 0-RAND_MAX.
`rand() % 115` returns a number in the range 0-114. Note that 115 < RAND_MAX.
`85 + rand() % 115;` This just adds 85 to above number so what you get is a number in the range 85-199.

Sigh. That's what I get for copying down the code blindly off the book. I see the issue now. However, the number keeps going up anyway - I suppose that is part of the time function?

Is there any way to generate random numbers one after the other without them being too lined up? (Like for example I keep getting increases such as 56, 65, 85, 114, 8, 15 as though it were on a clock)
Last edited on
Do you get these numbers by running the program many times? It probably has to do with the seed following the clock. If you run the program twice in the same second you will even get the same exact number. Generating many random numbers within the same run of the program will probably give numbers that appear to be more random.
Last edited on
I see, yea I was running the same program over and over again. Thanks much for the help!
Topic archived. No new replies allowed.