Cprogramming 简明教程

Random Number Generation in C

C 中的 stdlib.h 库包括 rand() 函数,该函数返回一个随机整数,介于“0”和常量 RAND_MAX 之间。

The stdlib.h library in C includes the rand() function that returns an integer randomly, between "0" and the constant RAND_MAX.

rand() 函数生成伪随机数。它们并非真正的随机数。此函数基于线性同余生成器 (LCG) 算法工作。

The rand() function generates pseudo-random numbers. They are not truly random. The function works on Linear Congruential Generator (LCG) algorithm.

int rand(void);

Example 1

以下代码调用 rand() 函数三次,每次都会返回一个不同的整数:

The following code calls the rand() function thrice, each time it is likely to come with a different integer −

#include <stdio.h>
#include<stdlib.h>

int main() {

   printf("%ld\n", rand());
   printf("%ld\n", rand());
   printf("%ld\n", rand());

   return 0;
}

Output

运行代码并检查其输出:

Run the code and check its output −

41
18467
6334

rand() 函数没有内置机制设置种子。默认情况下,它可能使用特定于系统的数值(通常基于程序启动的时间)。

The rand() function doesn’t have a built-in mechanism to set the seed. By default, it might use a system specific value (often based on the time the program starts).

Notesrand() 函数用于通过向 rand() 函数提供种子来改善随机性。

Note: The srand() function is used to improve the randomness by providing a seed to the rand() function.

Example 2

以下程序返回 0 到 100 之间的随机数。rand() 函数返回的随机整数用作分子,并计算其模 100 值以得到小于 100 的随机数。

The following program returns a random number between 0 to 100. The random integer returned by the rand() function is used as a numerator and its mod value with 100 is calculated to arrive at a random number that is less than 100.

#include <stdio.h>
#include<stdlib.h>

int main(){

   for(int i = 1; i <= 5; i++) {
      printf("random number %d: %d \n", i, rand() % 100);
   }

   return 0;
}

Output

运行代码并检查其输出:

Run the code and check its output −

random number 1: 41
random number 2: 67
random number 3: 34
random number 4: 0
random number 5: 69

Example 3

您还可以获取给定范围内的随机数。您需要求出 rand() 除以范围跨度的模值,并将结果添加到该范围的较小值。

You can also obtain a random number between a given range. You need to find the mod value of the result of rand() divided by the range span, add the result to the lower value of the range.

#include <stdio.h>
#include<stdlib.h>

int main() {

   int i, num;
   int lower=50, upper=100;

   for (i = 1; i <= 5; i++) {
      num = (rand() % (upper - lower + 1)) + lower;
      printf("random number %d: %d \n", i,num);
   }

   return 0;
}

Output

运行代码并检查其输出:

Run the code and check its output −

random number 1: 91
random number 2: 55
random number 3: 60
random number 4: 81
random number 5: 94

The srand() Function

stdlib.h 库还包括 srand() 函数,该函数用于设置 rand() 函数的随机数生成器的种子。

The stdlib.h library also includes the srand() function that is used to seed the rand() function’s random number generator.

您将使用以下 syntax 来使用 srand() 函数:

You would use the following syntax to use the srand() function −

void srand (unsigned seed);

OR

int srand (unsigned int seed);

seed 参数是一个整数值,将被伪随机数生成器算法用作种子。

The seed parameter is an integer value to be used as seed by the pseudo-random number generator algorithm.

Note : 如果 srand() 没有初始化,那么 rand() 函数中的种子值被设置为 srand(1)。

Note: If srand() is not initialized, then the seed value in rand() function is set as srand(1).

通常,srand() 函数与由 time(NULL) 返回的值(代表从纪元以来的当前时间)一起用作一个参数,以提高 C 中的 rand() 生成的伪随机数的随机性。

Usually, the srand() function is used with the value returned by time(NULL) (which represents the current time since the epoch) as a parameter to improve the randomness of the pseudo-random numbers generated by rand() in C.

由于时间值始终在改变,这将具有不同的种子值,从而导致更多样化的随机序列。结果,如果你多次生成随机数,那么每次都可能导致不同的随机值。

Since the time value changes all the time, this will have different seed values, leading to more varied random sequences. As a result, if you generate random number multiple times, then it will likely result in different random value every time.

Example 1

请看以下示例:

Take a look at the following example −

#include <stdio.h>
#include<stdlib.h>
#include <time.h>

int main() {

   srand(time(NULL));
   printf("Random number: %d \n", rand());

   return 0;
}

每次都将显示 0 到 RAND_MAX 之间的一个新随机整数。

Every time a new random integer between 0 to RAND_MAX will be displayed.

Random number: 1436786055

Example 2

我们可以包含 srand() 以在给定范围内生成一个随机数。

We can include srand() to generate a random number between a given range.

#include <stdio.h>
#include<stdlib.h>
#include <time.h>

int main() {

   int i, num;
   time_t t;
   int lower = 100, upper = 200;
   srand((unsigned) time(&t));

   for (i = 1; i <=5; i++) {
      num = (rand() % (upper - lower + 1)) + lower;
      printf("random number number %d: %d \n", i, num);
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

random number number 1: 147
random number number 2: 171
random number number 3: 173
random number number 4: 112
random number number 5: 181

rand() 函数提供的随机数生成并非真正的随机。使用相同的种子,你总是会得到相同的序列。它还有一个有限的范围,因为它会在一个特定范围内(0 到 RAND_MAX)生成随机数。

The random number generation offered by rand() function is not truly random. With the same seed, you’ll always get the same sequence. It also has a limited range as it generates random numbers within a specific range (0 to RAND_MAX).

为了提高随机性,你需要使用具有高度不可预测性的良好种子值,例如系统时间或高分辨率计时器。你还可以使用第三方库来获取更广泛范围的随机数。

To improving the Randomness, you need to use a good seed value with high unpredictability like system time or a high-resolution timer. You can also use third party libraries for wider range random numbers.