//与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)); }