How to control the range of random numbers in the C language?

In C language, the rand() function can be used to generate random numbers, where by default it generates an integer between 0 and RAND_MAX. If you want to control the range of the random numbers, this can be achieved through some mathematical calculations.

For example, if you want to generate a random number within the range of 0 to N, you can use the following code:

int random_number = rand() % (N + 1);

In the code above, rand() % (N + 1) will generate a remainder between 0 and N, and the range of remainders is exactly from 0 to N. Therefore, this method can be used to generate a random number between 0 and N.

To generate a random number between M and N (M < N), you can use the following code:

int random_number = M + rand() % (N - M + 1);

In the above code, rand() % (N – M + 1) will generate a remainder between 0 and N-M, which is then added to M to create a range of numbers from M to N. Consequently, this method can be used to generate a random number between M and N.

It is important to note that the rand() function in the code above will still generate a random number between 0 and RAND_MAX, so if you want to generate a larger range of random numbers, you can achieve this by calling the above code multiple times.

bannerAds