The function rand() can generate random numbers within a range like between 1 and 100 or 1 and 10. What if we want to generate the random numbers between 0 and 1? The numbers between 0 and 1 are the only numbers which are in fractions and by using the general method which we use for generating random numbers between 1 and 10, will not work since it can not print the floating points or the doubles. Further ahead we will discuss approach and the program itself for generating the random numbers between 0 and 1 and the result will be in float i.e., in decimals.

# Algorithm

Print “random numbers generated between 0 and 1 are ”

Use function srand(time(NULL)); to prevent the repetition of the sequence of random numbers.

Run a for loop for generating at least 5 random numbers.

Cast the return value of function rand() to float or double to get the return value in decimals. Otherwise you will get 0 as a return value.

`#include <time.h> #include <iostream> #include<cstdlib> using namespace std; int main() { cout<<"Random numbers generated between 0 and 1:"<<endl; srand( (unsigned)time( NULL ) ); for (int i = 0; i < 5; i++) { cout << (float) rand()/RAND_MAX << endl; } return 0; }`

### Output

Random numbers generated between 0 and 1: 0.260323 0.00625629 0.187323 0.916349 0.826228

### Conclusion

The whole method of generating the random numbers is similar to the general method except we have to cast the return value of the function rand() to double or float to get the values in decimals.