How to generate random numbers in the C language?

In C language, the rand() function can be used to generate random numbers. However, the sequence of random numbers generated is the same each time the program runs. To ensure that a different sequence of random numbers is generated each time, the srand() function can be used to set a seed value, commonly using the current time as the seed value.

Here is an example code for generating random numbers.

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

int main() {
    int i;
    int num;

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

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

    return 0;
}

In the above code, the srand(time(NULL)) function uses the current time as a seed value, and then the rand() function generates 10 random numbers, which are then printed out. Each time the program is run, a different sequence of random numbers is generated.

bannerAds