C++ primer6.21练习题(产生随机数的相关知识)

#include <iostream>  
#include <string>
#include<ctime>
#include<cstdlib>
using namespace std;

int MaxNum(const int xValue, const int *yValue) //有可能后面的int*指针是一个数组的首元素指针
{
	return xValue > *yValue ? xValue : *yValue;
}


int main()
{	
	srand((unsigned)time(NULL)); //生成随机数种子
	int a[10];
	for (auto &i : a)
		i = rand() % 10;
	int b;
	cin >> b;
	cout << "较大值为: ";
	cout << MaxNum(b, a)<<endl;
	cout << "数组全部元素为: ";
	for (auto j : a)
		cout << j << ' ';
	system("pause");
	return 0;
}


主要来看看srand() rand() time()函数

首先要明白的是:计算机并不能产生真正的随机数,而是已经编写好的一些无规则排列的数字存储在电脑里,把这些数字划分为若干相等的N份,并为每份加上一个编号用srand()函数获取这个编号,然后rand()就按顺序获取这些数字,当srand()的参数值固定的时候,rand()获得的数也是固定的。

那么srand()产生的编号在这里我们称为种子,一旦种子固定,产生的随机数序列也是固定了的。所以我们在使用rand()前,可以用srand()产生种子,如果直接调用rand(),默认是srand(1)。 而此程序中我们用srand((unsigned)time(NULL)) 来产生种子。也就是time()这个函数,time(NULL)返回当前的系统时间,我们再用强制转换为unsigned,这样就可以每次调用这个srand()时,产生的种子都不一定。这样伪随机数的随机性更大。


详细的产生随机数函数可以看看这个:http://blog.csdn.net/jx232515/article/details/51510336


发布了54 篇原创文章 · 获赞 14 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章