Generate random numbers in C++

In this post, we will discuss how to generate random numbers in C++.

 

1. std::rand()

The most common and simple solution is to use rand() function defined in the <cstdlib> header which generates a random number between 0 and RAND_MAX (both inclusive). To generate a different value every time, pass a seed to the function srand(), which should be another random value, preferably a value representing the current time.

 

Download   Run Code

 

2. C++11 – std::uniform_int_distribution

With C++11, several new features are introduced in the header <random>.

 
Below code uses std::uniform_int_distribution to uniformly generate random integer values between specified range distributed using a discrete probability function.

 

Download   Run Code

 
Instead of using std::random_device, we can use the chrono library to obtain a seed for the random number engine mersenne_twister_engine.

 

Download   Run Code

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Categories

Leave a Reply

avatar
  Subscribe  
Notify of