C++ to generate random Numbers of the implementation code

  • 2020-04-02 01:06:18
  • OfStack

How C++ generates random Numbers: the rand() function and srand() function are used here. There is no random(int number) function in C++.
(1) If you just generate random Numbers without setting a range, you just use rand() : rand() returns a random number between 0 and RAND_MAX. The RAND_MAX value is at least 32767.
Such as:

#include<stdio.h>
#include <iostream>


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

(2) If you were to randomly generate a number in a range,
For example, randomly generate 10 Numbers from 0 to 99:
The same code at the page code block index 0

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

In short, random Numbers in a~b range can be generated by: A + rand () % (b - a + 1)
(3) However, when the above two examples are run several times, the output is still the same as the first time. This has the advantage of being easy to debug, but it loses the meaning of random Numbers. If you want to generate different random Numbers for each run, you use the srand() function. Srand () is used to set the random number seed when rand() generates a random number. Before calling the rand() function to generate a random number, a seed must be set using srand(). If no seed is set, rand() automatically sets the seed to 1 when it is called. The above two examples are that because no random number seed is set, each random number seed is automatically set to the same value of 1, resulting in the same random number generated by rand().
Srand () function definition: void srand(unsigned int seed);
You can usually use the return value of geypid() or time(0) as seed
If you use time(0), you want to include the header #include < Time. H >
Such as:

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

In this way, the result of each run will be different!!

Related articles: