[C ++] brief notes - to generate random numbers

C language has a function of random data can be generated, to add the following headers:

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

In addition it should be added at the beginning of the main function

srand((unsigned)time(NULL));//生成随机数的种子

Srand which is used to initialize the random seed.
Then use the rand function where necessary using random numbers.
The following is a code for generating a random number:

#include <cstdio>
#include <time.h>
#include<stdlib.h>
int main()
{
	srand((unsigned)time(NULL));
	for (int i = 0; i < 10; i++)
	{
		printf("%d ", rand());
	}
	return 0;
}

It is noted that: rand () function only give [0, RAND_MAX] integer in the range , (and RAND_MAX stdlib.h is a constant in the different system environment value of this constant is different), so if you want to output a given range [a, b] in the random number, required rand ()% (b-a + 1) + a.
But such left and right end sections by not more than the random number RAND_MAX effective, if the need to generate a larger number, may generate a random number rand times with splice bit operation (or multiplied), may be randomly selected from each of a digital value, and then spliced into a large integer,Another idea: to generate a [0, RAND_MAX] using the random number in the range RAND (), then the random number obtained by dividing RAND_MAX a floating-point number in the range [0,1], the floating-point multiply and finally a length in the range of b-a + 1, plus a can, i.e.,

(int)((double)rand()/32767*(b-a+1)+a)//32767为该环境下的RAND_MAX

(The entire contents of the above is taken "algorithm Notes")

Published 43 original articles · won praise 4 · Views 1211

Guess you like

Origin blog.csdn.net/weixin_42176221/article/details/101772706