0

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]

Community
  • 1
  • 1
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104
  • 1
    Could you incorporate the information in the links into the post itself? – kaveish Apr 21 '16 at 22:08
  • Hey @kaveish, the functionality is summarized by the title of those links. Both are within positive range. I wanted to keep it clean here but I will include it. Thanks – Khalil Khalaf Apr 21 '16 at 22:12
  • 1
    The `c++11` method [here](http://stackoverflow.com/a/19652723/1885037) works for both positive and negative decimals. – kaveish Apr 21 '16 at 22:16
  • @kav my `std:: namespace` didn't recognize the codes so I dropped and looked for next else. Do you know why? – Khalil Khalaf Apr 21 '16 at 22:25
  • I would need more information, but make sure you compile with the `-std=c++11` flag if using `gcc`. – kaveish Apr 21 '16 at 22:29
  • Be aware that computers work in binary, not decimal. You can't actually generate `0.1` as that's an infinitely long binary number. – MSalters Apr 21 '16 at 23:00
  • @ms so if I do that more frequent it will consume a lot of processing power? – Khalil Khalaf Apr 22 '16 at 00:58

1 Answers1

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

Paul R
  • 208,748
  • 37
  • 389
  • 560