C++ 随机函数----谈rand() 和 srand() 体会


      在不少时候,程序中会用到随机数,在C++中就要用到专门用以产生随机数的标准库函数rand(),它会产生一个无符号整数,范围在0~32767,即两字节16位的整数最大值。而GNU C++产生的随机数范围为2147483647。 范围中的每个数在每次随机调用rand时都有相同的几率被选中。 ios

    调用时 ,须要引用头文件<cstdlib>,示例代码 函数

//掷20次筛子,每五个一行输出 spa

#include "stdafx.h" .net

#include <iostream>
using std::cout;
using std::endl;

#include <iomanip>
using std::setw ;

#include <cstdlib>
using std::rand;




int _tmain(int argc, _TCHAR* argv[])
{   


for(int i=1;i<=20;i++)
{
cout<<setw(10)<<(1+rand()%6);//比例缩放,6称为缩放因子
if(i%5==0)
{
 cout<<endl;
 
}

}
return 0;
}

  当咱们屡次执行后,咱们会发现每次执行的结果是同样的,既然是随机,这是为何呢??? blog

  这是由于,rand()产生的其实是一个伪随机数,若是要确保每次产生的都不同,咱们须要引用一个专门为rand设置随机化种子的函数srand().示例代码以下: ip

#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin ;
#include <iomanip>
using std::setw ;


#include <cstdlib>
using std::rand;
using std::srand;


int _tmain(int argc, _TCHAR* argv[])
{   
unsigned int seed;
     cout<<"输入随机化种子(它是一个无符号整数)";
cin>>seed;
srand(seed);




for(int i=1;i<=20;i++)

cout<<setw(10)<<(1+rand()%6);//比例缩放,6称为缩放因子
if(i%5==0)
{
 cout<<endl;
 
}

}
return 0;
}
结果1种子为:67 ci

2种子为76 get

3当再次执行后,种子仍然为76的时候,结果和上次执行的同样: io

  OK,,,, stream

原文链接:http://my.oschina.net/u/163141/blog/119433
相关文章
相关标签/搜索