srand在随机数发生器中的应用

在C++中srand()与rand()都包含在头文件 <cstdlib> 中,下面首先看一个投六面骰子的随机数发生程序

 

  1. /********************************************************** 
  2.         产生随机数发生器,范围1~6  产生20组数据 
  3. **********************************************************/  
  4. #include <iostream>  
  5. #include <iomanip> //setw()的头文件,setw()用来指定输出字符串宽度  
  6. #include <cstdlib>    
  7. using namespace std;  
  8.   
  9. int main()  
  10. {  
  11.     for(int i=1;i<=20;i++) //一共产生20组数据  
  12.     {  
  13.     cout<<setw(10)<<(1+rand()%6);  
  14.     if(i%5==0)  //每5个数据作为一行输出  
  15.     cout<<endl;  
  16.     }  
  17.   
  18.     return 0;  
  19. }  

其结果为:

 

6         6           5           5             6

5         1           1           5             3

6         6           2           4             2

6         2           3           4             1

 

但是多运行几次发现,上面每次的运行结果都一样。那是不是随机数不随机了呢?当然不是,当调试模拟程序时,对于证实程序的修改是否正确,这种重复性是至关重要的。

当调试完成后,可以设置条件使每次执行都产生不同的随机序列,这时就要用到srand()函数。srand函数是随机数发生器的初始化函数。

 

  1. #include <iostream>  
  2. #include <cstdlib>  
  3. #include <iomanip>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     unsigned int seed;  
  10.     cout<<"Enter seed: ";  
  11.     cin>>seed;  
  12.     srand(seed);  
  13.   
  14.     for(int counter=1;counter<=10;counter++)  
  15.     {  
  16.         cout<<setw(10)<<(1+rand()%6);  
  17.         if(counter%5==0)  
  18.         cout<<endl;  
  19.     }  
  20.   
  21.     return 0;  
  22. }  


srand()为随机数发生器提供种子数即程序中的seed,当输入的种子值不同时,就会产生不同的随机数序列。

 

但每次都输入一个种子值,会使人感到很不方便,因此可以使用这样的语句    srand( time(0) ).

这会是计算机读取它的时钟值,以获得种子值。time(0)会返回系统的当前值,即从格林尼治统一时间(GMT)1970年1月1日 午夜开始到现在的秒数。这个值会转化成一个无符号整数值,并作为随机数生成器种子。time函数 包含在头文件<ctime> 中。

 

    1. #include <iostream>  
    2. #include <ctime>  
    3. #include <cstdlib>  
    4. #include <iomanip>  
    5.   
    6. using namespace std;  
    7.   
    8. int main()  
    9. {  
    10.     srand(time(0));  
    11.   
    12.     for(int counter=1;counter<=10;counter++)  
    13.     {  
    14.         cout<<setw(10)<<(1+rand()%6);  
    15.         if(counter%5==0)  
    16.         cout<<endl;  
    17.     }  
    18.   
    19.     return 0;  
    20. }  

原文链接: https://www.cnblogs.com/hszeng/archive/2012/07/02/2573651.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    srand在随机数发生器中的应用

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/54250

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午5:27
下一篇 2023年2月9日 上午5:29

相关推荐