十进制生成范围内的随机数,包括负数?

Decimal Generate Random Number within a range including negatives?

我有以下函数来生成 min, max 范围内的随机数:

#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
}

我想在上面的函数中包含 c++ create a random decimal between 0.1 and 10 functionality or/and create a random decimal number between two other numbers 功能 而没有 排除负数。所以我想得到 "any" 范围之间的小数:[negative, negative][negative, positive][positive, positive]

您只需要确保 minmax 的顺序正确,并使用浮点数而不是整数,例如

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