设计随机库

来源:互联网 发布:python编程入门 epub 编辑:程序博客网 时间:2024/06/06 03:19

接口设计原则:
用途一致:接口中所有函数都属于同一类问题
操作简单:函数调用方便,最大限度隐藏操作细节
功能充足:满足不同潜在用户的需要
性能稳定:经过严格测试,不存在程序缺陷

在生成随机数过程中需要用到srand函数,以使每次重新运行程序生成的随机数没有相关性,实现绝对意义上的随机。

srand((int)time(0))介绍
srand函数需要接收一个参数,返回值没有,前面的s是种子的意思,就是说调用一次srand,将会设定随机数发生器的种子,决定随机数发生器初始值是几,如果程序运行的时候,每次初始的x0不一样,那么随机数发生器就会根据不同的x0,来替你生成随机数序列。
怎么让两次运行的初始值不一样,由于两次运行时的时间不一样,我们可以用当前时间直接转换成整数,作为srand这个函数的种子传进去。两次时间不一样,所以,两次得到的随机序列不一样。
srand函数在运行过程中只能调用一次,而且必须是在生成第一个随机数之前调用。

随机库的设计代码:
随机数库接口:

random_number.h文件

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

随机数库的实现:

random_number.cpp文件

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

测试代码:

main.cpp

#include<iostream>using namespace std;#include"random_number.h"int main(){    int i;    Randomize();    for(i=0;i<10;i++)    {        int t=GenerateRandomNumber(10,99);        cout<<t<<"  ";    }    cout<<endl;    for(i=0;i<10;i++)    {        double d=GenerateRandomReal(10.0,99.0);        cout<<d<<"  ";    }    cout<<endl;    system("pause");    return 0;}

运行结果:
这里写图片描述

0 0
原创粉丝点击