Super detailed explanation of random number generation in C language

1. First look at a simple code

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

int main(void)
{
	int i;printf(" %6d\n", rand());

        
	system("pause");
}

Run this program and you will find that every time you restart the program.

The random numbers generated are fixed, so how can they still be called random numbers?




2. Solution>srand()

srand() is to provide a seed to rand()

srand(time);//This can print out random numbers that meet the requirements, but we need to use the following form

In order to unify the time type and the srand type, use cast (unsigned):

srand((unsigned) time(NULL));

3. Random numbers that meet the needs

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

int main(void)
{
	int i;
	srand((unsigned)time(NULL));

	for (i = 0; i < 10; i++)
	{
		printf(" %6d\n", rand());
	}
	system("pause");
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325569857&siteId=291194637