Rand () and srand () [C language library function source code]

Source: Internet
Author: User
Tags random seed

[C language library function source code]

[This program is compiled in Dev C ++ 4.9.9.2]

/*

These two functions are programs that generate random numbers in the C library. You need to first

Use the srand () function to assign a random seed value. And then use

Rand () function to generate a random number. But the algorithm that generates random numbers

Relatively simple, the srandom () and random () functions are for these two functions

And the usage is similar.

*/

# Define random_max 0x7fffffff

 

Static long my_do_rand (unsigned long * value)

{

/*

This algorithm ensures that the generated value does not exceed (2 ^ 31-1)

Here (2 ^ 31-1) is 0x7fffffff. 0x7fffffff

Equal to 127773*(7 ^ 5) + 2836,7 ^ 5 = 16807.

The entire algorithm is through: t = (7 ^ 5 * t) mod (2 ^ 31-1)

This formula is used to calculate the random value and take the obtained value

The Random Seed value calculated next time.

*/

Long quotient, remainder, T;

 

Quotient = * value/127773l;

Remainder = * value % 127773l;

T = 16807l * remainder-2836l * quotient;

 

If (T <= 0)

T + = 0x7fffffffl;

Return (* value = T) % (unsigned long) random_max + 1 ));

}

Static unsigned long next = 1;

Int my_rand (void)

{

Return my_do_rand (& next );

}

 

Void my_srand (unsigned int seed)

{

Next = seed;

}

 

# Include <time. h>

Int main ()

{

Int I;

My_srand (unsigned) (Time (null )));

For (I = 0; I <100; I ++)

{

If (I % 10 = 0)

Printf ("/N ");

Printf ("% d/T", my_rand () % 99 + 1 );

}

System ("pause ");

Return 0;

}

 

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.