Random numbers are frequently used in programming for test case generation, cryptography, and other related purposes.

In this tutorial, we will generate random number between 0 and 1 in C++.

Table of Contents

## Using the `rand()`

function to generate random number between 0 and 1 in C++

The `rand()`

function is used to generate a random number in C++. To work with this function we need to import the `random`

library in C++. We can specify the range for the `rand()`

function.

To generate random number between 0 and 1, we use the following code.

1 2 3 4 5 6 7 8 9 10 11 |
#include <random> #include <iostream> using namespace std; int main() { for (int i = 0; i < 5; ++i) { cout << (float)rand() / (float)RAND_MAX << '\n'; } } |

Output:

0.394383

0.783099

0.79844

0.911647

In the above code,

- We generated 5 random numbers using the
`rand()`

function and running it 5 times using the`for`

loop. - The value for
`RAND_MAX`

constant is implementation-dependent and changes from compiler to compiler. - We typecast the final number to a
`float`

value.

It should be noted that whenever this code is run, the outcome will always be the same 5 random numbers. To fix this, we can use the `srand()`

function, which sets the starting point for random number generation.

It is not advisable to use a constant value for the `srand()`

function, so instead we use the `time()`

function which helps in generating a different sequence every time.

See the following code.

1 2 3 4 5 6 7 8 9 10 11 12 |
#include <random> #include <iostream> using namespace std; int main() { srand((unsigned) time(0)); for (int i = 0; i < 5; ++i) { cout << (float)rand() / (float)RAND_MAX << '\n'; } } |

Output:

0.980979

0.616666

0.0109556

0.953417

Another thing to remember is that the above method will include 0 and 1 as random numbers. We can exclude 1 from it, by adding 1.0 in the denominator making it `(float)(RAND_MAX + 1.0)`

## Using the `std::uniform_real_distribution()`

function to generate random number between 0 and 1 in C++

This function is used to generate float values between a given range. We can generate random number between 0 and 1 using this function as shown below.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <random> #include <iostream> using namespace std; int main() { random_device rd; mt19937 gen(rd()); uniform_real_distribution<> dis(0,1.0); for (int i = 0; i < 5; ++i) { cout << dis(gen) << '\n'; } } |

Output:

0.864206

0.830996

0.756512

0.206154

In the above example,

- The
`random_device`

initializes the seed for the random number generation engine. - We specify the
`<float>`

datatype, otherwise, the final output can be in`double`

or`long double`

type also. - The range for the numbers is specified in the
`dis()`

argument.

That’s all about C++ random number between 0 and 1.