代码:
/*
This is a free Program, You can modify or redistribute it under the terms of GNU
*Description: 随机数发生器,指定一个数,比如1000,要求随机产生1到1000之间的
任意数,并且1到1000之间任何一个数产生的概率是相等的,都是1/1000
*Language: C++
*Development Environment: VC6.0
*Author: Wangzhicheng
*Date: 2012/10/5
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
#define Max 1e10
typedef long Type;
template<class Type>
class RandomProducer {
private:
Type *N;
Type *random;
void setN(Type num) {
*N=num;
}
Type getN() const {
return *N;
}
void setRandom(Type r=0) {
*random=r;
}
Type getRandom() {
return *random;
}
void Producer() {
srand(unsigned(time(0)));
Type i;
Type k=1;
for(i=1;i<=getN();i++) {
if(rand()%k==0) setRandom(i);
k++;
}
/*
如果最终产生是1,那么必须保证第1次,第2次,...第N次都产生1,
Ai={第i次产生1},i=1,2,...N.
P(AN)=P(A1A2A3...AN)=P(A1)*P(A2|A1)*P(A3|A1A2)*...*P(AN|A1A2...AN-1)
=1*(1/2)*(2/3)*(3/4)*...((N-1)/N)=1/N
其余类推,所以按照以上方法,产生1到1000之间任意数的概率是1/N
*/
}
public:
RandomProducer(Type num) {
if(num<=0 || num>=Max) {
cerr<<"输入的数据必须大于0且小于"<<Max<<endl;
cerr<<"程序退出!"<<endl;
exit(1);
}
N=new Type;
setN(num);
random=new Type;
setRandom(0);
Producer();
}
~RandomProducer() {
delete N;
N=0;
delete random;
random=0;
}
void show() const {
cout<<"产生的随机数是:"<<*random<<endl;
}
};
void main() {
cout<<"Written By Wangzhicheng,CopyRight(C) 2012/10/5 "<<endl;
Type N;
cout<<"请输入一个大于0且小于"<<Max;
cout<<"的整数:";
cin>>N;
if(!cin.good()) {
cerr<<"输入格式非法,程序退出!"<<endl;
exit(1);
}
RandomProducer<Type>instance(N);
instance.show();
}
测试:
标签:...,void,random,发生器,简易,num,随机数,Type,1000 From: https://blog.51cto.com/u_15899033/5903541