首页 > 代码库 > c++随机数及rand()的缺陷

c++随机数及rand()的缺陷

c++生成随机整数和浮点数如下:

#include <random>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    cout << "随机数测试开始: " << endl;
    default_random_engine dre;
    uniform_int_distribution<int> di(10,20);
    for(int i=0;i<10;i++) {
        cout << di(dre) << " ";
    }
    cout << endl;

    uniform_real_distribution<double> dr(10,20);
    for(int i=0;i<10;i++) {
        cout << dr(dre) << " ";
    }
    cout << endl;

    vector<int> vs;
    vs.push_back(1);
    vs.push_back(2);
    vs.push_back(3);
    vs.push_back(4);
    vs.push_back(5);
    vs.push_back(6);
    vs.push_back(7);
    vs.push_back(8);
    vs.push_back(9);
    vs.push_back(0);
    shuffle(vs.begin(),vs.end(),dre);
    for(int i =0;i<vs.size();i++) {
        cout << vs[i] << " ";
    }
    cout << endl;
    cout << "随机数测试结束. " << endl;
}

输出如下:

随机数测试开始:
16 13 20 19 14 17 10 16 15 14
10.9754 15.4722 12.785 11.8838 15.4688 19.9288 19.5751 19.9646 19.6489 19.6769
0 3 2 9 5 1 6 7 4 8
随机数测试结束.

还可以使用标准C的rand,如下:

#include <cstdlib>
int main() {
    //srand(10);
    for(int i = 0; i < 10; i ++)
            cout << rand() << " "; //返回0~32767之间
    cout << endl;
}

输出如下:

41 18467 6334 26500 19169 15724 11478 29358 26962 24464

关于使用随机数引擎还是rand()函数的问题,在C++标准库第二版17.1.1看到如下说明:

技术分享

 

c++随机数及rand()的缺陷