#include <iostream>
#include <map>
using namespace std ;
#include <time.h>
#include <math.h>
//C語言的庫函數rand有以下兩個可改進之處
//範圍太小,才3萬多,改成40億多
//需要srand,如果不srand 預設隻是1。CRand預設值是clock()。注意:Windows下GetTickCount更精确
#define ULONG unsigned long
//接口
class IRand
{
public:
//不實作SetSeed防止多次SetSeed引起種子值相同。構造函數中初始化種子
virtual ULONG Rand()=0;
};
class CRand : public IRand
{
public:
CRand(ULONG s1 = clock(),ULONG s2 = time(NULL) )
{
m_iSeed1 = s1 ;
m_iSeed2 = s2 ;
}
ULONG Rand()
{
ULONG b;
b = m_iSeed1 ^ (m_iSeed1 >> 2) ^ (m_iSeed1 >> 6) ^ (m_iSeed1 >> 7);
m_iSeed1 = (m_iSeed1 >> 1) | (~b << 31);
b = (m_iSeed2 << 1) ^ (m_iSeed2 << 2) ^ (m_iSeed1 << 3) ^ (m_iSeed2 << 4);
m_iSeed2 = (m_iSeed2 << 1) | (~b >> 31);
return m_iSeed1 ^ m_iSeed2;
}
protected:
ULONG m_iSeed1;
ULONG m_iSeed2;
};
void main()
{
const int n = 100;
CRand r ;
for( int i = 0 ; i < n ; i++ )
{
cout << r.Rand() << endl ;
}
}