码迷,mamicode.com
首页 > 编程语言 > 详细

C++ Random 的使用

时间:2018-09-25 19:38:44      阅读:930      评论:0      收藏:0      [点我收藏+]

标签:ref   bsp   修改   ber   style   rand   固定   cells   efault   

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

 

C++ Random 的使用

标签:ref   bsp   修改   ber   style   rand   固定   cells   efault   

原文地址:https://www.cnblogs.com/xiaoniu-666/p/9701347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!