Random number generator isn't working???

Oct 27, 2012 at 12:29am
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int number;

    unsigned seed;

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

    number = 85 + rand() % 115;

    cout<<number<<endl;

    cin.get();
    return 0;
}
Oct 27, 2012 at 12:41am
Do you understand how the % operator works?
Oct 27, 2012 at 12:44am
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...
Oct 27, 2012 at 12:52am
And do you understand operator precedence?
Oct 27, 2012 at 12:53am
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.

Oct 27, 2012 at 12:57am
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 Oct 27, 2012 at 1:03am
Oct 27, 2012 at 1:04am
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 Oct 27, 2012 at 1:05am
Oct 27, 2012 at 1:07am
I see, yea I was running the same program over and over again. Thanks much for the help!
Topic archived. No new replies allowed.