第一种是传统的方法:
#include <iostream>using namespace std;int main() {srand(NULL);for (int i = 0; i < 100; i++) {cout << rand() << ' ';}return 0;}
这种方法比较传统,缺点是随机性不够好,而且不能自己选择生成的随机数的范围。
以及如果你短时间内多次调用srand(NULL)
,生成的随机数是相同的:c - srand(time(NULL)) doesn’t change seed value quick enough - Stack Overflow
新的C++11的做法如下:
#include <iostream>#include <random>int main() {std::random_device rd;//Get a random seed from the OS entropy device, or whateverstd::mt19937_64 eng(rd()); //Use the 64-bit Mersenne Twister 19937 generator//and seed it with entropy.//Define the distribution, by default it goes from 0 to MAX(unsigned long long)//or what have you.std::uniform_int_distribution<unsigned long long> distr;//Generate random numbersfor (int n = 0; n < 40; n++){std::cout << distr(eng) << ' ';}std::cout << std::endl;}
比如说你想生成1-6的随机数,做法如下:
#include <random>#include <iostream>int main() {std::random_device rd;//Get a random seed from the OS entropy device, or whateverstd::mt19937_64 eng(rd()); //Use the 64-bit Mersenne Twister 19937 generator//and seed it with entropy.//Define the distribution, by default it goes from 0 to MAX(unsigned long long)//or what have you.std::uniform_int_distribution<unsigned long long> distr(1, 6);// distribution in range [1, 6]//Generate random numbersfor (int n = 0; n < 40; n++) {std::cout << distr(eng) << ' ';}std::cout << std::endl;}
参考:c++ - Generating random integer from a range - Stack Overflow