2011年计算机二级C++实例编程辅导2_第3页

考试站(www.examzz.com)   【考试站:中国教育考试第一门户】   2011年11月10日
 unsigned long randSeed;

  public:

  // 构造函数,默认值0表示由系统自动产生种子

  RandomNumber(unsigned long s = 0);

  // 产生0 ~ n-1之间的随机整数

  unsigned short Random(unsigned long n);

  // 产生[0, 1) 之间的随机实数

  double fRandom();

  };

  #endif

  类实现文件RandomNumber.cpp :

  代码

  // RandomNumber.cpp

  #include "RandomNumber.h"

  #include

  #include

  #include

  using namespace std;

  // 产生种子

  RandomNumber::RandomNumber(unsigned long s)

  {

  if(s == 0)

  randSeed = time(0); //用系统时间产生种子

  else

  randSeed = s;

  }

  // 产生0 ~ n-1 之间的随机整数

  unsigned short RandomNumber::Random(unsigned long n)

  {

  randSeed = multiplier * randSeed + adder;

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

  }

  // 产生[0, 1)之间的随机实数


相关文章