c++ - Decimal Generate Random Number within a range including negatives? -


i have below function generate random number within 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 first time only!         first = false;     }      return min + rand() % (max - min); // returns random int between specified range } 

i want include c++ create random decimal between 0.1 , 10 functionality or/and create random decimal number between 2 other numbers functionality above function without excluding negatives. want decimal between "any" range: [negative, negative], [negative, positive] , [positive, positive]

you need make sure min, max ordered correctly, , use floating point rather 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


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -