C++ 随机数生成的2种方法--生成指定范围内的随机数

第一种是传统的方法:

#include 

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 
#include 

int main() {
    std::random_device rd;     //Get a random seed from the OS entropy device, or whatever
    std::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 numbers
    for (int n = 0; n < 40; n++){
        std::cout << distr(eng) << ' ';
    }
    std::cout << std::endl;
}

比如说你想生成1-6的随机数,做法如下:

#include 
#include 

int main() {
    std::random_device rd;     //Get a random seed from the OS entropy device, or whatever
    std::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 numbers
    for (int n = 0; n < 40; n++) {
        std::cout << distr(eng) << ' ';
    }
    std::cout << std::endl;
}

参考:c++ - Generating random integer from a range - Stack Overflow

你可能感兴趣的:(c++,linux)