[Solved] Is there a random function that generates numbers between 0 and 1 [closed]


There’s the rand() function from <cstdlib> library, which returns a number between 0 and RAND_MAX. If you want a number between 0 and 1, you have to do a workaround with casts and divisions:

double X = ((double)rand() / (double)RAND_MAX);

This is a practical example, putting the previous code inside a function:

#include <cstdlib> //  srand, rand
#include <ctime> // time
#include <iostream> //std::cout

double random01()
{
     return ((double)rand() / (double)RAND_MAX);
}

int main()
{

    srand(time(0)); // Remember to generate a seed for srand

    for(int i=0; i< 100; ++i)
    {
        std::cout << random01()  << '\n';
    }

    return 0;
}

solved Is there a random function that generates numbers between 0 and 1 [closed]