C ++ generates random numbers

Source: Internet
Author: User

C ++ generates random numbers
Description

// Srand plays an important role here. srand () serves to initialize the random number seed and calculate the pseudo-random number of the seed,
// If the seeds are the same, the calculated random number is also the same. Generally, instead of srand (), the function uses rand (), which is equivalent to calling srand (1 ),
// This also solves the same problem when I re-run the program when I was playing the last memory game last semester.
// The value returned by time (NULL) is the number of seconds that have elapsed since, so every moment is different.

Code
# Include
  
   
# Include
   
    
// Time () # include
    
     
// Srand () + rand () int main () {srand (time (NULL); // generate [a, B] int m = rand () % a + B; printf ("% d \ n", m);} // The main function is to generate a random number, but the random number range generated by the rand () function is [0, RAND_MAX] // RAND_MAX must be at least 32767 (2e15-1), and the values may be different under different conditions. // here, the author uses the amplification method to enlarge the range (the code is from Liu rujia) # include
     
      
# Include
      
        // Time () # include
       
         // Srand () + rand () int n = 100, m = 100000; // This function is a real number within the range [0, 1, in the next function, increase (n-1) times to get the integer double random () {return (double) rand ()/RAND_MAX;} int random (int m) {return (int) (random () * (m-1) + 0.5);} int main () {srand (time (NULL); printf ("% d \ n ", n, m); for (int I = 0; I <m; I ++) {if (rand () % 2 = 0) {printf ("A") ;}else {printf ("B") ;}int X, Y; for (;) {X = random (n) + 1; Y = random (n) + 1; if (X! = Y) {break;} printf ("% d \ n", X, Y);} return 0 ;}
       
      
     
    
   
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.