C++中使用Rand()函数来产生“随机数”,实际上还要使用一个名为Srand()的函数产生种子,系统通过种子和随机数产生算法,生成不同的数字。当我们在使用Rand()没有调用Srand()时,系统会自动调用Srand(),种子相同时,产生的随机数相同。
为了能更好的产生随机数,我们通常使用系统时间作为随机数种子。
// srandTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream> //输入输出用到的头文件
#include <time.h> //time 用到的头文件
#include <Windows.h> //Sleep 用到的头文件
using namespace std;
void testRand(void); //函数原型
void testSrand(void);//函数原型
int _tmain(int argc, _TCHAR* argv[])
{
cout << "*************testRand**************" << endl;
testRand();
cout << "\r\n*************testSrand**************" << endl;
testSrand();
cin.get();//捕获输入种子后的ENTER键
cin.get();
return 0;
}
void testRand()
{
int cinNum, coutNum;
for (int i = 0; i < 5; ++i)
{
cout << "please enter a number as seed:" << endl;
cin >> cinNum;
srand(cinNum); //将输入的数字作为种子
for (int i = 0; i < 5; ++i)
{
coutNum = rand() % 100; //产生1-100以内的随机数
cout << "random number:" << coutNum << endl;
}
}
}
void testSrand()
{
int coutNum;
for (int i = 0; i < 5; ++i)
{
cout << "generate seed by system time" << endl;
Sleep(1478); //设置程序休眠时长,若不设置,则由于计算机处理速度过快,系统时间相同,种子相同
srand((unsigned)time(NULL));
for (int i = 0; i < 5; ++i)
{
coutNum = rand() % 100;
cout << "random number:" << coutNum << endl;
}
}
}
结果如下