Marco Lau
Marco Lau

Reputation: 619

srand() and rand() favors producing negative numbers

I wrote this function to produce random numbers within a certain range. I noticed that it seems to produce negative numbers more when I included a negative range. e.g. -5 to 5

I am assuming this is not random. Is there a problem with this code?

int random_number_generator(int lowest, int highest)
{
    srand((unsigned)time(0));
    int random_integer;
    random_integer = lowest+(rand()%highest);
    cout << random_integer << endl;
}

Upvotes: 2

Views: 3925

Answers (3)

axelBrain
axelBrain

Reputation: 46

result of next expression is rand number within [ lowest .. highest ] interval

random_integer = lowest + ( rand( ) % (highest-lowest + 1) );

Upvotes: 0

Martin Perry
Martin Perry

Reputation: 9527

You can use this code:

int srandInit = 0;
float Random(float min, float max)
{
    if (srandInit == 0) 
    {
        srand ( (unsigned)time(NULL) );
        srandInit = 1;
    }
    return ((max - min) * ((float)rand() / (float)RAND_MAX)) + min;
}

and just make static_cast from float result to int

Upvotes: 1

krisku
krisku

Reputation: 3991

The desired range would be highest-lowest, so you need to write the expression like this:

random_integer = lowest+(rand()%(highest-lowest));

Upvotes: 5

Related Questions