zoukankan      html  css  js  c++  java
  • C++ 随机函数谈rand() 和 srand() 体会

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

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

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

    #include "stdafx.h"

    #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;
    }

      当我们多次执行后,我们会发现每次执行的结果是一样的,既然是随机,这是为什么呢???

      这是因为,rand()产生的实际上是一个伪随机数,如果要确保每次产生的都不一样,我们需要引用一个专门为rand设置随机化种子的函数srand().示例代码如下:

    #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

    2种子为76

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

      OK,,,,

  • 相关阅读:
    JSON的序列化与还原
    正则表达式的一些基础
    跨域二三事
    与Web服务器通信
    与 Web 服务器通信
    代码重构
    构造函数与各种继承方法特点
    this指向问题——严格、非严格模式,事件处理程序
    《JavaScript设计模式与开发实践》学习笔记——单例模式
    Git常用命名及常见操作流程
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3002622.html
Copyright © 2011-2022 走看看