C random number, random number

Source: Internet
Author: User

C random number, random number

 

This is a bit of a pitfall. The results are the same every time, so good random is not random. In fact, the random number itself is also calculated, and each time it is calculated by the random number seed. If the random number seed is different, the calculated random number is different, and the function that generates the random number seed is also in stdlib. h. The function is srand ().

[This part of code is in function1]

We need to give random number seeds different values each time, and then we can get different random numbers, but there is another drawback. How can a seed get different values. We know that time is different all the time, so if we can use time to give the random number seed, the results will be different each time.

Get

 

The result is better.

 

The following source code.

 

 

# Include <iostream> # include <stdlib. h> # include <time. h>/** rand () from stdlib. h file */void function1 (void); void function2 (void); // int [] makeArray (int array []); // how to return an array of the int type? Void display (int array []); int main () {function1 (); function2 (); return 0;} void function2 (void) {int array [10]; int randomseed = (int) time (NULL); // contained in time. in h, // return the current time. The time type must be forcibly converted to the int type. Srand (randomseed); for (int I = 0; I <10; I ++) {array [I] = rand () ;}display (array );} void function1 (void) {// we use rand () to generate a random number: int array [10]; for (int I = 0; I <10; I ++) {array [I] = rand ();} display (array);} void display (int array []) {for (int I = 0; I <10; I ++) {printf ("array [I] = % d", array [I]); if (I + 1) % 5 = 0) {printf ("\ n ");}}}

 

 

Related Article

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.