Share: C++ code to generate random numbers

 

This article is a detailed analysis and introduction of the implementation code for generating random numbers in C++. Friends who need it can refer to the following

How C++ generates random numbers: The rand() function and srand() function are used here. There is no built-in random(int number) function in C++.


(1)  If you only need to generate random numbers without setting the range, you only need to use rand(): rand() will return a random value ranging from 0 to RAND_MAX. The RAND_MAX value is at least 32767.
For example:

code show as below:

#include<stdio.h>
#include <iostream>
 
code show as below:

int _tmain(int argc, _TCHAR* argv[])
{
       for(int i=0;i<10;i++)
             cout << rand() << endl;
}

(2)  If you want to randomly generate a number within a certain range,
for example: randomly generate 10 numbers from 0 to 99:
code show as below:

#include<stdio.h>
#include <iostream>
 
code show as below:

int _tmain(int argc, _TCHAR* argv[])
{
     for(int x=0;x<10;x++)
           cout << rand()%100 << " ");
}


In short, to generate random numbers in the range of a~b, available:  a+rand()%(b-a+1)


(3) However, when the above two examples are run multiple times, the output results are still the same as the first time. The advantage of this is that it is easy to debug, but it loses the meaning of random numbers. If you want to generate different random numbers for each run, you will use the srand() function. srand() is used to set the random number seed when rand() generates random numbers. Before calling the rand() function to generate random numbers, you must use srand() to set the random number seed (seed). If no random number seed is set, rand() will automatically set the random number seed to 1 when calling. The above two examples are because the random number seed is not set, and the random number seed is automatically set to the same value 1 each time, which leads to the same random value generated by rand().


srand() function definition: void srand (unsigned int seed);
Usually you can use the return value of geypid() or time(0) as a seed
If you use time(0), you need to add the header file #include<time.h >
For example:

code show as below:

#include<stdio.h>
#include<time.h>                               
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
 srand((unsigned)time(NULL)); //srand((unsigned)time(0))   srand((int)time(0) 均可
for(int i=0;i<10;i++)
cout << rand() << endl;
}

In this way, the results will be different every time you run it! !

Reprinted from: Weidian Reading   https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131767548