How to set the range of the rand() function in C language?

In the C language, when using the rand function to generate random numbers, the default range for the generated random number is from 0 to RAND_MAX, where the value of RAND_MAX is usually 32767. To generate random numbers within a specified range, you can use the modulus operation.

For example, if you want to generate a random number between 0 and 9, you can use the following code:

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

To generate a random number within a specific range, you can use the following formula:

int random_num = rand() % (max - min + 1) + min; // 生成min到max之间的随机数

In this case, min and max represent the minimum and maximum values of the desired range of random numbers. For example, if you want to generate a random number between 1 and 100, you can use the following code:

int random_num = rand() % 100 + 1; // 生成1到100之间的随机数
bannerAds