C / C ++: rand () function
rand () function in the header file: #include <stdlib.h>
Randomness of the random numbers generated by a difference function, slow, small period (0-32767)
Are used as follows:
. 1 #include <stdio.h> 2 #include <stdlib.h> . 3 #include <time.h> . 4 int main () . 5 { . 6 srand ((unsigned int ) Time ( 0 )); /// to lapse system time of the random number generator seed . 7 for ( int I = 0 ; I < 10 ; I ++ ) . 8 { . 9 int (n-= RAND ()% 50 - 25 ) + 25 ; /// random integer generated between 25-50 , rand% (ba) + a which produce [a, random integers in b) the range of 10 Double D = RAND () / (Double ) and RAND_MAX; /// generating a random decimal 0-1 . 11 the printf ( " % D% F \ n- " , n-, D); 12 is } 13 is the puts ( "" ); 14 the printf ( " RAND () function can be generated random number range: 0-% D \ n- " , and RAND_MAX); 15 return 0 ; 16 }
Code results are as follows:
C++11:mt19937
mt19937 header file: #include <random>
Generating speed, large period (0-4294967295)
Usage above rand () Similarly, as shown below:
1 #include<random> 2 #include<time.h> 3 #include<bits/stdc++.h> 4 using namespace std; 5 int main() 6 { 7 mt19937 mt_rand(chrono::high_resolution_clock::now().time_since_epoch().count());///随机种子 8 ///或用:mt19937 mt_rand(time(0)); 9 for(int i=0;i<10;i++) 10 { 11 int n=mt_rand()%(1000-25)+25; /// generates random integer between 25-1000 12 is the printf ( " % D \ n- " , n-); 13 is } 14 return 0 ; 15 }
Random library using a random number generator, used as follows:
. 1 #include <the iostream> 2 #include <Random> . 3 the using namespace STD; . 4 . 5 int main () . 6 { . 7 mt19937 are RNG; . 8 rng.seed (random_device () ()); // initialize the random seed . 9 10 uniform_int_distribution < int > int_dist ( 1 , 100 ); // create a uniform distribution equiprobable (random) to generate [1, 100] interval digital shaping; . 11 uniform_real_distribution < Double > real_dist (- 1 , 1 ); //Creating a uniform distribution (equiprobable) randomly generated between the (-1, 1) decimal; 12 is 13 is for ( int I = 0 ; I < 10 ; I ++ ) { 14 COUT << int_dist (RNG) << ' ' ; 15 COUT << real_dist (RNG) << endl; 16 } . 17 return 0 ; 18 is }
Results are as follows:
C ++ Standard Library --random