随机化算法(随机数产生并模拟抛硬币实验)

源代码来自王晓东算法设计与分析

#include "stdafx.h"
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include "stdafx.h"
#include"iostream"
#include<math.h>
#include<time.h>
#include<iomanip>
using namespace std;
const unsigned long maxshort=65535L;
const unsigned long multiplier=1194211693L;
const unsigned long adder=12345L;
class RandomNumber{
private:
 //当前种子
 unsigned long randSeed;
public:
 //构造函数
 RandomNumber(unsigned long s=0);
 unsigned short Random(unsigned long n);
 double fRandom();
};


RandomNumber::RandomNumber(unsigned long s)
{
 if(s==0)
  randSeed=time(0);
 else
  randSeed=s;
}

double RandomNumber::fRandom()
{
 return Random(maxshort)/double(maxshort);
}

unsigned short RandomNumber::Random(unsigned long n)
{
 randSeed=multiplier*randSeed+adder;
 return (unsigned short)((randSeed>>16)%n);
}

 

int TossCoins(int numberCoins)
{
 //随机抛硬币
 static RandomNumber coinToss;
 int i,tosses=0;
 for(i=0;i<numberCoins;i++)
  tosses+=coinToss.Random(2);
 return tosses;
}

 

int _tmain(int argc, _TCHAR* argv[])
{
 const int NCOINS=10;
 const long NTOSSES=50000L;
 long i,heads[NCOINS+1];
 int j,position;
 for(j=0;j<NCOINS;j++)
  heads[j]=0;
    for(i=0;i<NTOSSES;i++)
  heads[TossCoins(NCOINS)]++;
 for(i=0;i<=NCOINS;i++)
 {
  position=int(float(heads[i])/NTOSSES*72);
  cout<<setw(6)<<i<<" ";
  for(j=0;j<position-1;j++)
   cout<<" ";
  cout<<"*"<<endl;
 }
    int x;
 while(1){
 cin>>x;
 if(x==1) return 0;
 }
}

 

 

你可能感兴趣的:(算法,Random,float)