C language - how to generate random numbers?

rand function 

 In C language, rand function is used to generate pseudo-random numbers . Its prototype is as follows: int rand(void);                             

The rand function returns an integer ranging from 0 to RAND_MAX, where RAND_MAX is a constant representing the maximum value of a random number. The value of RAND_MAX is 32767 . Because its value has a maximum range limit, the rand function is called a pseudo-random number . However, we can optimize the range of random numbers generated by the rand function through the srand function .

If you want to generate a random number within a specified range, you can use the remainder operator. For example, if you want to generate a random number in the range 0 to 9, you can use rand() % 10 . This will return an integer between 0 and 9.

srand function

In C language, the srand function is used to set the seed of a random number generator.

Its prototype is as follows: void srand(unsigned int seed);

Among them, seed is an unsigned integer used to initialize the seed of the random number generator. Normally, we use the time function to obtain the current time as a seed to ensure that the random number sequence generated is different each time the program is run.

Examples are as follows:

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

int main() {
    int i;
    
    // 使用时间作为种子
    srand((unsigned int)time(NULL));
    
    // 生成并打印10个随机数
    for (i = 0; i < 10; i++) {
        printf("%d\n", rand());
    }

    return 0;
}

In the above example, srand((unsigned int)time(NULL)) passes the time as a seed to the srand function, and then generates 10 random numbers through the rand function and prints them out. Since the seed changes over time, you will get a different sequence of random numbers every time you run the program.

Why cast (unsigned int)?

In some compilers and compilation environments, time(NULL) the return value of may be  time_t a type, while  srand the function's parameters are  unsigned int types. The purpose of  time(NULL) casting to  unsigned int a type is to ensure that the types match and avoid compiler warnings.

Therefore, it   is a good practice to time(NULL) add it in front of it  to ensure that the program can run normally under different compilation environments and avoid type mismatch problems. (unsigned int)Doing so improves the portability of your code.

Guess you like

Origin blog.csdn.net/m0_73800602/article/details/131950580