使用随机数

随机数的使用非常普遍,现在总结一下随机数的生成的方法;

C:

rand()产生随机数:

使用库:stdlib.h+time.h

较长使用的是rand(void)函数,它是根据一个随机数种子在一个算法下,产生一个小范围内可看成随机数的一个函数,因为随机数种子在不改变的时候每次调用rand()都是相同的结果,因此,在少量的数据时,我们完全可以使用rand()函数产生随机数,对rand()函数取余的到目标范围:rand()%n(生成0-n 的随机数)

srand((unsigned)time(NULL))设置一个随机数种子

由于随机数种子不变,因此rand()仍然可以看作是一个有序的数列,因此,我们如果想产生更加随机的随机数,改变随机数种子是一个很好的办法,

其中time(NULL)时当前时间的毫秒值。

示例代码:

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h> 
#include<time.h>

//#include<map>
#include<set>
#include<deque>
#include<queue>
#include<stack>
#include<string>
#include<fstream> 
#include<iostream>
#include<algorithm>
using namespace std;

#define ll long long
#define INF    0x3f3f3f3f
#define clean(a,b) memset(a,b,sizeof(a))// 雷打不动的头文件

int main()
{
	srand((unsigned)time(NULL));
	for(int i=0;i<10;++i)
		cout<<rand()<<endl;
}

output:


猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/80965458