这是一个封装了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;
}
编译运行输出如下:
再次运行
两次运行生成了不同的随机数列,且两种方法都是可行的。