Datastructure c++ note 3a

来源:互联网 发布:逆战有没有刷枪软件 编辑:程序博客网 时间:2024/05/29 15:03

//注意求比率时(int a < int b)  a / b = 0 , 要转换为 float(a) / float(b)

#include "stdafx.h"

#include <ctime>

using namespace std;

 

 

//用当前种子产生随机数

const unsigned long maxshort = 65536L;

const unsigned long multiplier = 1231523651L;

const unsigned long adder = 12345L;

 

 

class RandomNumber

{

public:

     //缺省值0表示系统自动给出种子

     RandomNumber(unsigned long s = 0);

     ~RandomNumber(){};

 

 

     //产生0 <= value <= n-1 的随机整数

     unsigned short Random(unsigned long n);

 

 

     //产生0 <= value <= 1.0 的随机实数

     double fRandom(void);

 

 

 

 

private:

     //存放当前种子的私有成员

     unsigned long m_randomSeed;

};

 

 

RandomNumber::RandomNumber(unsigned long s)

{

     if (0 == s)

         m_randomSeed = time(0);

     else

         m_randomSeed = s;

}

 

 

unsigned short RandomNumber::Random(unsigned long n)

{

     //得到一个32位数

     m_randomSeed = m_randomSeed * multiplier + adder;

    //得到16位的数并映射到0 <= value <= n-1

     return (unsigned short)(( m_randomSeed >> 16 ) % n);

 

 

}

 

 

double RandomNumber::fRandom()

{

    return Random(maxshort)/double(maxshort);

}

 

 

//投掷numCoins, 并返回正面朝上的次数, random(2) = 1 表示正面朝上

int TossCoins(int numCoins)

{

     //声明static 保证每次都使用独立的随机数列的下一个数(防止相同)

     static RandomNumber num; 

     int tossResult = 0;

     for (int i=0; i<numCoins; i++)

     {

        tossResult += num.Random(2);

     }

     return tossResult;

}

 

 

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

{

    

 

 

     //投一个硬币,多少次朝上?

    static RandomNumber num(5);

 

 

     int tossNumbers = 5000;

    int result = 0;

     for (int i=0; i < tossNumbers; i++)

     {

         result += num.Random(2);

 

 

     }

     cout << result << endl;

 

 

     //每次投递的硬币数目,投递的次数

    const int nCoinsNum = 10;

     const int tossTimes = 5000;

 

 

     //head[0]0个硬币朝上,head[10]10个硬币朝上

     int head[nCoinsNum + 1];

    //初始化数组

     for(i=0; i<nCoinsNum+1; i++)

            head[i] = 0;

 

 

     for(i=0; i<tossTimes; i++)

         head[TossCoins(nCoinsNum)]++;

 

 

     for(i=0; i<nCoinsNum; i++)

     {

         int position = (int)((float)head[i] / (float)tossTimes * 72);

         cout << i << " ";

        

         for(int j=0; j<position; j++)

              cout << " ";

 

 

         cout << "*" << endl;

     }

        

 

 

 

 

 

 

     cout << num.Random(5) << endl;

     cout << num.Random(5) << endl;

     cout << num.fRandom() << endl;

     cout << num.fRandom() << endl;

 

 

     return 0;

}

原创粉丝点击