+ 1
Random number
How to make a random number generation in c++
4 Respostas
+ 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;
}
+ 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/
+ 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);
}
}
+ 1
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main() {
srand(time(0));
int x = 1+rand()%1000;
cout<<x;
}