c++随机数,rand,srand

rand() 和 srand()

简介:

rand 和 srand 都是标准程序库提供的伪随机数产生器

srand的参数是随机数产生器种子seed

每次调用rand,都会返回一个介于0和int能表示的最大值之间的一个整数

头文件:

rand,srand均在cstdlib中:

#include<cstdlib>

用法:

算法的细节还没有仔细研究,可能是利用线性同余,hash函数等方式

但是请注意,要达到你的随机目的,需要先自己找到一个足够随机的数作为种子seed,调用srand(seed),否则每次都将得到相同的随机数序列。

我们做一些演示:

for(int i=0;i<4;i++){
	cout<<rand()<<"\t";
}

反复运行以上代码,你将得到相同的结果,虽然可能与我得到的结果不太一样。

output-1:

41      18467   6334    26500

output-2:

41      18467   6334    26500

但是当你设置了不同的seed,情况将发生变化:

for(int seed=0;seed<4;seed++){
	srand(seed);
	for(int i=1;i<4;i++){
		cout<<rand()<<"\t";
	}
	cout<<endl;
}

output:

38      7719    21238   2437
41      18467   6334    26500
45      29216   24198   17795
48      7196    9294    9091

猜你喜欢

转载自www.cnblogs.com/qishihaohaoshuo/p/12747172.html