(1)、C++标准函数库提供一随机数生成器rand(),函数说明:int rand(); 返回[0,MAX]之间均匀分布的伪随机整数,这里的MAX与你所定义的数据类型有关,必须至少为32767。rand()函数不接受参数,默认以1为种 子(即起始值)。随机数生成器老是以相同的种子开始,因此造成的伪随机数列也相同,失去了随机意义。(但这样便于程序调试)
html
#include "stdafx.h" //预编译头
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int x = rand();
cout << x << endl;
getchar();
return 0;
}
ios
能够发现,每次运行程序,rand()获得的序列值是不变的,都为41。
ide
(2)、C++中另外一函数srand(),能够指定不一样的数(无符号整数变元)为种子。可是若是种子相同,伪随机数列也相同。一个办法是让用户输入种子,可是仍然不理想函数
(3)、比较理想的是用变化的数,好比时间来做为随机数生成器的种子。time的值每时每刻都不一样。因此种子不一样,产生的随机数也不一样。调用srand()函数后,rand()就会产生不一样的随机序列数。ui
#include "stdafx.h" //预编译头
#include <time.h>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand((unsigned)time(NULL));
int x = rand();
cout << x << endl;
getchar();
return 0;
}
url
能够发现,每次运行程序,rand()获得不一样的序列值:1146,1185,...spa
对上段程序改写:调试
#include "stdafx.h" //预编译头
#include <time.h>
#include <iostream>
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;
}htm
运行结果:产生0-9之间的10个随机整数。blog
若是要产生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://blog.163.com/wujiaxing009@126/blog/static/719883992011113011359154/
http://blog.sina.com.cn/s/blog_4c740ac00100d8wz.html
http://baike.baidu.com/subview/10368/12526578.htm?fr=aladdin&qq-pf-to=pcqq.c2c