(1)、C++标准函数库提供一随机数生成器rand(),函数说明:int rand();
返回[0,MAX]之间均匀分布的伪随机整数,这里的MAX与你所定义的数据类型有关,必须至少为32767。rand()函数不接受参数,默认以1为种
子(即起始值)。随机数生成器总是以相同的种子开始,所以形成的伪随机数列也相同,失去了随机意义。(但这样便于程序调试)
#include "stdafx.h" //预编译头
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int x = rand();
cout << x << endl;
getchar();
return 0;
}
可以发现,每次运行程序,rand()得到的序列值是不变的,都为41。
(2)、C++中另一函数srand(),可以指定不同的数(无符号整数变元)为种子。但是如果种子相同,伪随机数列也相同。一个办法是让用户输入种子,但是仍然不理想
(3)、比较理想的是用变化的数,比如时间来作为随机数生成器的种子。time的值每时每刻都不同。所以种子不同,产生的随机数也不同。调用srand()函数后,rand()就会产生不同的随机序列数。
#include "stdafx.h" //预编译头
#include
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL));
int x = rand();
cout << x << endl;
getchar();
return 0;
}
可以发现,每次运行程序,rand()得到不同的序列值:1146,1185,...
对上段程序改写:
#include "stdafx.h" //预编译头
#include
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL));
for (int i = 0; i < 10; i++){
int x = rand() % 10;
cout << x << endl;
}
getchar();
return 0;
}
运行结果:产生0-9之间的10个随机整数。
如果要产生1~10之间的10个整数,则是这样:int x = 1 + rand() % 10;
总结来说,可以表示为:a + rand() % n,其中的a是起始值,n是整数的范围。
a + rand() % (b-a+1) 就表示 a~b之间的一个随机数,比如表示3~50之间的随机整数,则是:int x = 3 + rand() % 48;包含3和50.
http://baike.baidu.com/subview/10368/12526578.htm?fr=aladdin&qq-pf-to=pcqq.c2c