How to use the random function in the C language?

To use the random function in C language, you need to include the header file . The specific method of use is as follows:

  1. The rand() function is called to generate pseudo-random numbers. This function returns a random integer between 0 and RAND_MAX (including 0 and RAND_MAX). RAND_MAX is a constant defined in that represents the maximum value of a random number.
  2. To generate a random number within a specific range, you can scale the random number using modulo operation. For example, to generate a random number between 0 and 9, you can use rand() % 10.
  3. To ensure that a different sequence of random numbers is generated each time the program is run, you can use the srand() function to set the random number seed. By passing an integer value as the seed, you can typically use the time(NULL) function to get the current time as the seed, ensuring that the seed is different each time the program is run.

Below is an example code demonstrating how to use a random function to generate a random number between 0 and 9.

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

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

    // 生成0到9之间的随机数
    int randomNum = rand() % 10;

    printf("Random number: %d\n", randomNum);

    return 0;
}

Each time the program is run, the output of the random number may be different.

bannerAds