C + + generates random numbers

Source: Internet
Author: User

Description

Here the role of Srand is very important, the role of Srand () is to initialize the random number seed, the seed pseudo-random number calculation basis,
Similarly, the calculated random number is the same, usually the function is not practical to srand () but with Rand (), it is equivalent to calling the Srand (1),
It also took me to the last semester when I did the final memory game. Every time you execute the program again, the random number that is generated is the same problem.
The value returned by Time (NULL) is the number of seconds since the 1970.1.1 zero, so every moment is different

Code
#include <stdio.h>#include <time.h> //time () #include <stdlib.h> //srand () +rand () intMain () {Srand (Time (NULL));//Generate [A, b]    intm = rand ()% a + B;printf("%d\n", m);}//Generate random numbers primarily. But the RAND () function generates a random number interval of [0,rand_max]//rand_max is at least 32767 (2e15-1), and the values may differ under different conditions//Here The author uses a magnified way to enlarge the interval (code from Rujia)#include <stdio.h>#include <time.h> //time () #include <stdlib.h> //srand () +rand () intn = -, M =100000;//This function is to get the real number within the [0,1] interval, and then expand (n-1) times in the next function to the roundingDoubleRandom () {return(DoubleRAND ()/Rand_max;}intRandomintm) {return(int) (Random () * (M-1) +0.5);}intMain () {Srand (Time (NULL));printf("%d%d\n", N, m); for(inti =0; I < m; i++) {if(rand ()%2==0)        {printf("A"); }Else{printf("B"); }intX, Y; for(;;) {X = random (n) +1; Y = Random (n) +1;if(X! = Y) { Break; }        }printf("%d%d\n", X, Y); }return 0;}

C + + generates random numbers

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.