c++中random的方法


参考博客

https://www.cnblogs.com/xiaoniu-666/p/9701347.html

rand方法

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

int N = rand() % 11; 

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

int N = 1 + rand() % 10;

总结来说,可以表示为:

a + rand() % n 

random库使用

c++11才有的方法

#include <iostream> 
#include <random>
using namespace std;
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 namespace std;
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;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM