+ 1

Random number

How to make a random number generation in c++

28th Jun 2024, 1:03 PM
Khang Bùi
Khang Bùi - avatar
4 ответов
+ 3
#include <iostream> #include <random> using namespace std; int main() { random_device rd; mt19937 rng(rd()); uniform_int_distribution<int> randint(1,100); int n = randint(rng); cout << n <<endl; }
28th Jun 2024, 2:50 PM
Bob_Li
Bob_Li - avatar
+ 3
https://cplusplus.com/forum/beginner/251751/ random from chrono is an older and simpler method inherited from C. random is more sophisticated and gives you more choices and options. Mersenne Twister pseudo-random generator https://cplusplus.com/reference/random/mt19937/
28th Jun 2024, 3:41 PM
Bob_Li
Bob_Li - avatar
+ 2
I ran the code provided by Bob_li, it works quit fine and I like the fact that it's very short but I haven't seen those weird typing (mt19937) used in production before. I'm not sure how popular it is. The common implementation I've seen is much longer and uses <ctime> or <chrono> to seed the random engine. #include <random> #include <chrono> using rd = std::default_random_engine; float randRange(rd& e, const float& min, const float& max) { std::uniform_real_distribution<float> d(min, max); return d(e); } int main() { rd e; e.seed(std::chrono::high_resolution_clock().now().time_since_epoch().count()); cout << randRange(0, 10); } }
28th Jun 2024, 3:11 PM
Mel
+ 1
#include <iostream> #include <cstdlib> #include <time.h> using namespace std; int main() { srand(time(0)); int x = 1+rand()%1000; cout<<x; }
29th Jun 2024, 5:28 AM
Alhaaz
Alhaaz - avatar