1 函数原型
rand():生成随机数,函数原型如下:
int rand (void);
cstdlib库描述如下:
Generate random number
1. Returns a pseudo-random integral number in the range between 0 and RAND_MAX.
2. This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called.
3. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.
4. RAND_MAX is a constant defined in <cstdlib>.
5. A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range :
(1) v1 = rand() % 100; // v1 in the range 0 to 99
(2) v2 = rand() % 100 + 1; // v2 in the range 1 to 100
(3) v3 = rand() % 30 + 1985; // v3 in the range 1985-2014
6. Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).
- rand()函数:
(1)用于生成一个伪随机数; - 注意事项
(1)伪随机性:rand()函数生成的数看似随机,但实际上是由一个确定的算法和初始条件(即种子)决定的;如果不设置种子或总是使用相同的种子,rand()函数将产生相同的随机数序列;
(2)随机数范围:rand()函数返回的随机数是一个介于0和RAND_MAX之间的整数;其RAND_MAX是一个常量,表示rand()函数能返回的最大值,通常是32767;
(3)随机数分布:rand()函数生成的随机数分布是均匀的,即在给定的范围内,每个数被选中的概率大致相等。
2 参数
rand()函数的参数为void。
3 返回值
rand()函数的返回值类型为int型:
- 返回一个介于0到RAND_MAX之间的整数。
cstdlib库描述如下:
1. An integer value between 0 and RAND_MAX.
4 使用方法
4.1 基本用法
在使用rand()函数之前,通常需要调用srand()函数来设置随机数生成的种子:
- srand()函数通常只被调用一次,且通常在程序的开始处调用,其参数可以是任何整数;
- 通常使用time()函数获取当前时间作为种子,因为每次程序运行时当前时间都是不同的,从而能够生成不同的随机数序列。
4.2 生成指定范围内的随机数
虽然rand()函数直接返回的是0到RAND_MAX之间的随机数,但你可以通过一些简单的数学运算来生成指定范围内的随机数。例如,要生成一个介于a和b(包括a和b)之间的随机数,可以这样做:
int min = a;
int max = b;
int randNum = min + rand() % (max - min + 1);
这里的%是取模运算符,用于限制rand()函数生成数的范围。
特别注意 模运算可能会导致生成的随机数在指定范围内不是完全均匀分布的;特别地,当RAND_MAX不是目标范围的整数倍时,这种方法会使范围内的某些数(尤其是低数值)的出现概率略高于其他数。
5 示例
示例代码如下所示:
int main() {
//
int random_number = 0;
// 设置随机数种子
srand((unsigned)time(0));
// 生成并打印 10 个随机数
for (int i = 0; i < 10; i++) {
// 生成随机数
random_number = rand();
printf("Random Number %2d: %d\n", i + 1, random_number);
}
//
return 0;
}
代码运行结果如下图所示:
- 第1次运行代码
- 第2次运行代码