How to generate a random number in the C language?

In C language, you can use the standard library function rand() to generate random numbers. The rand() function will return a random integer between 0 and RAND_MAX.

To generate a random number within a specified range, you can follow these steps:

  1. Include the standard library in the program.
  2. random number generator
  3. Generate a random number
  4. maximum value that can be generated by the rand function
  5. Can you please explain that concept more clearly?
  6. Assign the generated random number to a variable for future use.

Here is an example code for generating random integers between 1 and 100.

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

int main() {
    int randomNumber;
    
    // 使用当前时间来初始化随机数发生器
    srand(time(NULL));
    
    // 生成1到100之间的随机整数
    randomNumber = rand() % 100 + 1;
    
    printf("随机数: %d\n", randomNumber);
    
    return 0;
}

It is important to note that before using the `rand()` function, you need to first call the `srand()` function to initialize the random number generator. Typically, the current time can be used as a seed for initialization to ensure that each time the program runs, the generated random numbers are different. In the example code above, `srand(time(NULL))` is using the current time to initialize the random number generator.

Also, in order to use the time() function, it is necessary to add the header file .

bannerAds