C++ Random 的使用

1、rand() 方法

 rand()不需要参数,它会返回一个从0到最大随机数的任意整数,最大随机数的大小通常是固定的一个大整数。 这样,如果你要产生0~10的10个整数,可以表达为: 

 
int N = rand() % 11;

     这样,N的值就是一个0~10的随机数,如果要产生1~10,则是这样: 

 
int N = 1 + rand() % 10;

 总结来说,可以表示为:  

 
a + rand() % n

2、random库使用

#include <iostream> 
#include <random>
using std::cout; using std::endl;      
using std::default_random_engine;
int main()      
{       
    default_random_engine e;       
    for (size_t i = 0; i < 10; ++i) //生成十个随机数       
       cout << e() << endl;       
    cout << "Min random:" << e.min() << endl; //输出该随机数引擎序列的范围       
    cout << "Max random:" << e.max() << endl;       
    return 0;       
}

--修改随机种子

#include <iostream>
#include <random>

using std::cout; using std::endl;
using std::default_random_engine;

int main()
{
    default_random_engine e; //或者直接在这里改变种子 e(10) 
    e.seed(10); //设置新的种子
    for (size_t i = 0; i < 10; ++i)
       cout << e() << endl;
    cout << "Min random:" << e.min() << endl;
    cout << "Max random:" << e.max() << endl;
    
    return 0;
}

 

参考 :

https://www.cnblogs.com/byhj/p/4149467.html

http://www.cplusplus.com/reference/random/?kw=random

 

posted @ 2018-09-25 18:31  戒骄戒躁-沉淀积蓄  阅读(3811)  评论(0编辑  收藏  举报