随机数生成函数(封装rand,srand)

这是一个封装了srand()和rand()的函数

int random(int start, int end) {
    static bool first = true;
    if (first) {
        srand((unsigned int)time(NULL));
        first = false;
    }
        return start + rand() % (end - start + 1);
}

他接受两个参数作为随机数的范围,以time()作为种子。
除了封装为一个函数,我们还可以这样:

#define RANDOM(start,end) start + rand() % (end - start + 1)
#define SRAND srand((unsigned int)time(NULL))

可以在主函数中试验这两种方法。
完整代码为:

#include<iostream>
#include<time.h>
#include<stdlib.h>
#define RANDOM(start,end) start + rand() % (end - start + 1)
#define SRAND srand((unsigned int)time(NULL))
using namespace std;
int random(int start, int end) {
    static bool first = true;
    if (first) {
        srand((unsigned int)time(NULL));
        first = false;
    }
        return start + rand() % (end - start + 1);
}
int main() {
    //函数法
    for (int j = 0;j < 10;j++)
        cout << random(5, 20) << ' ';
    cout << endl;
    //宏法
    SRAND;
    for (int j = 0;j < 10;j++)
        cout << RANDOM(5,20) << ' ';
    cout << endl;
}

编译运行输出如下:
在这里插入图片描述

再次运行
在这里插入图片描述
两次运行生成了不同的随机数列,且两种方法都是可行的。

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值