Decimal Generate Random Number within a range including negatives?

时间:2016-04-21 22:01:01

标签: c++ random dynamically-generated

I have the below function to generate a random number within a min, max range:

#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

//..

int GenerateRandom(int min, int max) //range : [min, max)
{
    static bool first = true;
    if (first)
    {
        srand(time(NULL)); //seeding for the first time only!
        first = false;
    }

    return min + rand() % (max - min); // returns a random int between the specified range
}

I want to include c++ create a random decimal between 0.1 and 10 functionality or/and create a random decimal number between two other numbers functionality into the above function without excluding negatives. So I want to get the decimal between "any" range: [negative, negative], [negative, positive] and [positive, positive]

1 个答案:

答案 0 :(得分:1)

You just need to make sure that min, max are ordered correctly, and use floating point rather than integers, e.g.

double GenerateRandom(double min, double max)
{
    static bool first = true;
    if (first)
    {
        srand(time(NULL));
        first = false;
    }
    if (min > max)
    {
        std::swap(min, max);
    }
    return min + (double)rand() * (max - min) / (double)RAND_MAX;
}

LIVE DEMO