实现一个随机数库

//与5.1类似,只不过这不是用一个函数实现,还涉及到自个儿构建一个头文件

//main

#include<iostream>
using namespace std;
#include"random.h"//自个儿的头文件用“ ”,来包含;
int main()
{
	int i;
	Randomize();
	for(i=0;i<5;i++)
	{
		int t= GenerateRandomNumber(1,52);
		cout<<t<<endl;
	}
	cout<<endl;
for(i=0;i<5;i++)
	{
		double b= GenerateRandomreal(1.0,52.0);
		cout<<b<<endl;
	}
	return 0;
}

 接口random.h

void Randomize();
int GenerateRandomNumber(int low,int high);
double GenerateRandomreal(double low,double high);

  源文件

#include<iostream>
#include<cstdlib>
#include<ctime>
#include"random.h"
using namespace std;
void Randomize()
{
srand((int)time(NULL));
}
int GenerateRandomNumber(int low,int high)
{
double _d;
if(low>high)
{
cout<<"GenerateRandomNumber:Make sure low <= high 
";
exit(1);
}
_d=(double)rand()/((double)RAND_MAX+1.0);
return (int)(low+(_d*(high-low+1.0)));
}
double GenerateRandomreal (double low,double high)
{
double _d;
if(low>high)
{
cout<<"GenerateRandomreal:Make sure low <=high. 
";
exit(2);
}
_d=(double)rand()/(double)RAND_MAX;
return(low+_d*(high-low));
}

  

 

作者:这些年读过的书
出处: http://www.cnblogs.com/chenzinumber1/
本文版权归作者与博客园所有,欢迎转载,但未经作者同意必须保留此段声明,文末要留有原文链接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/chenzinumber1/p/8119887.html