C++ srand() and rand() usage

Refer to the usage of C++ rand and srand
The random numbers of the computer are all pseudo-random numbers, that is, generated by small M polynomial sequences, and each small sequence has an initial value, that is, a random seed. (Note: The period of the small M polynomial sequence is 65535, that is, the period of the random number generated by using a random seed each time is 65535, and they reappear after you get 65535 random numbers.) We know that the rand() function
can It is used to generate random numbers, but this is not a random number in the true sense, it is a pseudo-random number, which is a series of numbers calculated based on a certain recursive formula based on a number (we can call it a seed). When this series of numbers is very large, it conforms to the normal announcement, which is equivalent to generating random numbers, but this is not a real random number. When the computer is turned on normally, the value of this seed is fixed, unless you destroy the system .

rand()

usage

int rand();

head File

#include<stdlib.h>

code example

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

using namespace std; 

int main()
{
    
     
     for(int i=0;i<5;i++) cout << rand() << endl;
     return 0;
}
first run

insert image description here

second run

insert image description here

#####The third run
insert image description here
found that the random numbers generated by each run were the same.

srand()

The random numbers generated by rand() are the same each time. If you want to generate different random numbers each time, you can use srand() to initialize;

usage

void srand(unsigned int seed)

head File

#include<stdlib.h>

srand() is used to set the random number seed when rand() generates random numbers. The parameter seed must be an integer. If the seed is set to the same value every time, the random value generated by rand() will be the same every time.
You can use the method of srand((unsigned int)(time(NULL)) to generate different random number seeds, because the time of running the program is different each time.

first run

insert image description here

second run

insert image description here

third run

insert image description here

Generate a range of random numbers

Refer to the usage of C++ rand and srand

  • To get a random integer in [a,b), use (rand() % (ba))+ a;
  • To get a random integer in [a,b], use (rand() % (b-a+1))+ a;
  • To get a random integer of (a,b], use (rand() % (ba))+ a + 1;
  • General formula: a + rand() % n; where a is the starting value and n is the range of integers.
  • To get a random integer between a and b, another representation: a + (int)b * rand() / (RAND_MAX + 1).
  • To obtain a floating point number between 0 and 1, you can use rand() / double(RAND_MAX).

Guess you like

Origin blog.csdn.net/qaaaaaaz/article/details/130454050