+ 3

How do i generate a random number within a fixed range in c++?

29th Oct 2017, 5:32 AM
Hakshay Sundar
Hakshay Sundar - avatar
2 Answers
+ 6
#include<iostream> #include<random> #include<chrono> using namespace std; int main() { int low = 0; //Lower End of Range. int up = 20; //Upper End of Range. unsigned seed = system_clock::now(). time_since_epoch().count(); default_random_engine with_time_seed(seed); // The seed, linked with the current time. uniform_int_distribution <int> rand (low,up); //Declaration of a better rand. for (int i=0; i<10; ++i) cout<<rand(with_time_seed)<<endl; } You may use this in C++11, as this is better than rand. The variation is greater and numbers are truly pseudo random.
29th Oct 2017, 4:06 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar