How to generate random numbers in C language


1. rand function:

int rand( void );

Let’s take a look at the basic information of the rand function first:
Insert image description here
The rand function generates random values ​​based on the seed, but the seed is fixed each time the program runs. If you only use it, it actually returns is a pseudo-random integer.
Look at the red line in the picture above: the pseudo-random integer returned by the rand function. Before calling rand, you must first use the srand function to set the seed for the pseudo-random number generator.

2. srand function:

void srand( unsigned int seed );

Let’s take a look at the basic information of the srand function:
Insert image description here
We can see from the function prototype that srand requires a seed parameter of an unsigned integer. If srand is passed in every time If the seeds are the same, then the random values ​​generated by the rand function are also the same, which is not random in a certain sense.

Then the question is, if we want the random value to be random enough, we also need a random seed~
Usually we use time as the seed for random number generation, because every time the program runs The time is not the same, so the random numbers generated must also be different.

3. time function:

time_t time( time_t *timer );

Let’s take a look at the basic information of the time function:
Insert image description here
We only need to pass the null pointer NULL to the time function, and it will return the current time to us The timestamp of the time. In this case, the time seed can be used to generate random numbers.

Demo code:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
    
    
	srand((unsigned int)time(NULL));
	int ret = rand();
	printf("%d\n", ret);
	return 0;
}

4. Formula for generating range random numbers:

Many times we need to generate a random value with a range: for example 1~100.

Actually this is very simple:

srand((unsigned int)time(NULL));
int ret1 = rand() % 10 + 1;//生成1~10的随机数
int ret2 = rand() % 100 + 1;//生成1~100的随机数
int ret3 = rand() % 34 + 66;//生成66~99的随机数
int ret4 = rand() % (n - m + 1) + m;//生成m~n的随机数

5. Practical exercises:

A practical exercise to generate random numbers:
Click this article:C language number guessing game


Summarize

The above is what I will talk about today about generating random numbers in C language, including the use of rand, srand and time functions. I hope it will be helpful to you who have just read this blog.

Guess you like

Origin blog.csdn.net/weixin_61661271/article/details/123741988