What are the uses of rand and srand in the C language?

In C language, the rand() function is used to generate a pseudo-random number, which returns an integer between 0 and RAND_MAX. RAND_MAX is a constant defined in the stdlib.h header file, typically representing 32767.

The srand() function is used to set the seed for the random number generator. It takes one parameter as the seed, usually using the current time as the seed to ensure that a different sequence of random numbers is generated each time the program is run.

Here is an example of how to use the rand() and srand() functions:

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

int main() {
   int i;

   // 设置种子
   srand(time(NULL));

   // 生成10个随机数
   for(i = 0; i < 10; i++) {
      printf("%d ", rand());
   }

   return 0;
}

The code above uses srand(time(NULL)) to set the current time as the seed, then generates 10 random numbers using rand() and prints them out. Due to the different seed, every time the program is run, a different sequence of random numbers will be obtained.

bannerAds