提供一个随机数发生器的类,比rand()函数产生的随机数好(重复周期长),有興趣的話可以用在VB裏麵```
// Random.h
class CRandom
{
public:
CRandom();
CRandom::CRandom(LPCSTR strKey){RandShuffle(strKey);}
virtual ~CRandom();
void RandShuffle(const CString strKey); //初始化
double RandReal(double x,double y);
double RandNormal(double mean,double stddev);
int RandInteger(int a,int b);
double RandFrac(void);
double RandExponential(double mean);
long Rand(void);
private:
long m_nDataList[100];
};
//------------------------------------------------------------------------
//Random.cpp
#include "stdafx.h"
#include "Random.h"
#include <math.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CRandom::CRandom()
{
}
CRandom::~CRandom()
{
}
void CRandom::RandShuffle(const CString strKey)
{
CString key = "Abra Ca Da Bra" + strKey + CString(' ',83);
key = key.Left(97);
int i; char c;
for(i = 0; i <97; i++){
c = key.GetAt(i);
m_nDataList[i] =c * 8171717 + i +997;
}
key ="";
i = 96;
int j = 11;
for(int k = 0; k < 997; k++){
m_nDataList[i] = m_nDataList[i] - m_nDataList[j];
if(m_nDataList[i] < 0) m_nDataList[i]+=1000000000;
if(i>0){
i -= 1;
}
else{
i = 96;
}
if(j >0){
j -= 1;
}
else{
j = 96;
}
}
m_nDataList[97] = 55;
m_nDataList[98] = 24;
m_nDataList[99] = 77;
}
long CRandom::Rand()
{
long i = m_nDataList[97];
long j = m_nDataList[98];
int t = m_nDataList[i] - m_nDataList[j];
if(t <0) t+=1000000000;
m_nDataList[i] = t;
if(i>0)
m_nDataList[97] = i -1;
else
m_nDataList[97] = 54;
if(j>0)
m_nDataList[98] = j - 1;
else
m_nDataList[98] = 54;
i = m_nDataList[99] % 41 +55;
m_nDataList[99] = m_nDataList[i];
m_nDataList[i] = t;
return m_nDataList[99];
}
double CRandom::RandExponential(double mean)
{
return (-mean * log(RandFrac()));
}
double CRandom::RandFrac()
{
return (Rand() /1e9);
}
int CRandom::RandInteger(int a, int b)
{
ASSERT(a < b);
return (a + (Rand() % (b - a + 1)));
}
double CRandom::RandNormal(double mean, double stddev)
{
double u1 = RandFrac();
double u2 = RandFrac();
double x = sqrt(-2 * log(u1)) * cos(6.283185 * u2);
return (mean + stddev * x);
}
double CRandom::RandReal(double x, double y)
{
return (x + (y-x) * Rand() / 1e9);
}