About the random number generation function rand ()

Source: Internet
Author: User

In the vs environment, stdlib. H has the following definitions:

 

/* Maximum value that can be returned by the rand function .*/

# Define rand_max 0x7fff

 

Implementation in rand. C:

 

Void _ cdecl srand (
Unsigned int Seed
)
{
_ Getptd ()-> _ holdrand = (unsigned long) seed;
}

 

Int _ cdecl rand (
Void
)
{
_ Ptiddata PTD = _ getptd ();

Return (PTD-> _ holdrand = PTD-> _ holdrand * 214013l
+ 2531011l)> 16) & 0x7fff );
}

 

As you can see, in Vs, this function returns a maximum of 65535/2 regardless of the number;

 

In GCC, stdlib. H is defined:

 

128/* the largest number rand will return (same as int_max ).*/
129 # define rand_max 2147483647

 

Source codeIn glibc;

The following sectionCodeTo handle the differences between the two platforms:

 

Srand (Time (null ));

Bool bscale = (rand_max <= 65535 );

STD: Set setindex;
for (INT I = 0; I <500; I ++)
{< br> unsigned int unumrand = rand ();
If (bscale)
{< br> unumrand * = 65535;
}< br> setindex. insert (unumrand % 1000000);
}

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.