How to generate a random number in the C language?

In the C language, the rand() function can be used to generate a random number.

Firstly, you need to include the stdlib.h header file, which contains the declaration of the rand() function.

Then, you can use the srand() function to set the seed of the random number, which determines the starting point of the random number sequence. Typically, time(NULL) can be used as the seed, using the current time as the starting point.

Next, we can use the rand() function to generate random numbers. The rand() function returns a random integer between 0 and RAND_MAX.

Here is an example program that uses random numbers:

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

int main() {
    int i;
    int randomNum;

    srand(time(NULL)); // 设置随机数种子

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

    return 0;
}

In the above code, the srand(time(NULL)) function is used to set the random number seed, then the rand() function is used to generate 10 random numbers, which are then printed out.

It is important to note that the random numbers generated by the rand() function are pseudo-random numbers generated based on a predetermined algorithm, not truly random numbers. If higher quality random numbers are needed, consider using alternative libraries or algorithms to achieve this.

Leave a Reply 0

Your email address will not be published. Required fields are marked *