Random number generation in C

First of all, you must add a few header files: #include, #include, and then add a sentence "srand ((unsigned) time (NULL))" at the beginning of the main function. This statement will generate a random number seed and then use the ranf () function to generate random number. Examples are as follows:

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

At the same time, the rand () function can only generate integers in the range of [0, RAND_MAX]. RAND_MAX is a constant of cstdlib, which is different in different environments. The book I read is 32767.
If you want to output a random number in a fixed range [a, b], you need to use rand ()% (b-a + 1) + a, obviously the range of rand ()% (b-a + 1) is [0, ba ], Plus a is [a, b], generate numbers in the range of [0,1] and [3,7] as follows:

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

But these methods can only generate a boundary less than 32767, if you want to be larger, you can use multiple times to generate rand random numbers, and then use bit operation to splice together (or directly multiply two random numbers), another idea is to first Use rand () to generate a random number of [0, RAND_MAX], and then divide this number by RAND_MAX, and you will get a floating-point number in the range of [0,1]. We just need to multiply the floating point number by the length of the range (b-a + 1) and add a, ie (int) ((double) rand () / 32767 * (b-a + 1) + a) , Equivalent to this floating-point number is the proportional position in the range [a, b]. For example, to generate a random number in the range [10000,60000]:

int main(){
	srand((unsigned)time(NULL));
	for(int i=0;i<10;i++){
		printf("%d ",(int)(round(1.0*rand()/RAND_MAX*50000+10000)));
	}
	return 0;
}
Published 19 original articles · Likes2 · Visits 743

Guess you like

Origin blog.csdn.net/zan1763921822/article/details/104330271
Recommended