欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-19 20:56:00
...

第一种是传统的方法:

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

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