【C/C++】随机数的生成

C/C++:rand()函数

rand()函数的头文件:#include<stdlib.h>

该函数产生的随机数随机性差,速度慢,周期小(0-32767)

用法如下所示:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
    srand((unsigned int)time(0));///以系统流逝时间为随机数发生器种子
    for(int i=0;i<10;i++){
        int n=rand()%(50-25)+25; ///产生25-50间的随机整数,rand%(b-a)+a即产生[a,b)范围内的随机整数
        double d=rand()/(double)RAND_MAX; ///产生0-1的随机小数
        printf("%d  %f\n",n,d);
    }
    puts("");
    printf("rand()函数可产生随机数的范围:0—%d\n",RAND_MAX);
    return 0;
}

代码运行结果如下:

C++11:mt19937

mt19937的头文件:#include<random>

产生速度快, 周期大(0-4294967295)

用法与上述rand()类似,具体如下所示: 

#include<random>
#include<time.h>
#include<bits/stdc++.h>
using namespace std;
int main()
{
    mt19937 mt_rand(chrono::high_resolution_clock::now().time_since_epoch().count());///随机种子
    ///或用:mt19937 mt_rand(time(0));
    for(int i=0;i<10;i++){
        int n=mt_rand()%(1000-25)+25; ///产生25-1000间的随机整数
        printf("%d\n",n);
    }
    return 0;
}

使用random库进行随机数生成,用法如下所示:

#include <iostream>
#include <random>
using namespace std;

int main()
{
    mt19937 rng;
    rng.seed(random_device()());//初始化随机种子

    uniform_int_distribution<int> int_dist(1,100);//创建一个均匀分布,等概率(随机)生成[1, 100]区间的整形数字;
    uniform_real_distribution<double> real_dist(-1, 1);//创建一个均匀分布,(等概率)随机生成在(-1, 1)之间的小数;

    for(int i=0;i<10;i++){
        cout << int_dist(rng) << ' ';
        cout << real_dist(rng) << endl;
    }
    return 0;
}

运行结果如下:

C++标准库——random

随机排列:random_shuffle

STL中的random_shuffle(begin, end)函数用于对一个元素序列进行随机化的重新排序。

作用之一:快速排序面对较为有序的数列的效率较低, 而打乱顺序能有效提升快排速度的稳定性。

#include<iostream>
#include<algorithm>
#include<ctime>
using namespace std;
int main()
{
	srand((unsigned)time(NULL));
	char a[5] = {'a', 'b', 'c', 'd', 'e'};
	for(int j = 0; j<10 ; j++) {	
		random_shuffle(a,a+5);
		for(int i = 0; i < 5; i++) 
			cout << a[i];
		cout << endl;
	}
} 



运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值