Random Number in C #

Source: Internet
Author: User
Tags random seed

By default, the pseudo-random number generator random in C # sets its seed based on the system time.

Random RD = new random ();

Int randnum = RD. Next (1,101)

 

If we use the default method and do not assign any parameters to the random during initialization, the random seed takes the system time. If we use a loop to generate multiple random numbers at a time, because the CPU operation speed is too fast, so each time we get the same time, that is, the generated random number will be the same, therefore, the random number seed must be replaced before a random number is generated each time.

In this case, we can use an encrypted random number generator to generate different seeds. Each time we need to generate a random number, we can assign different seeds to random, even in a short period of time, different random numbers can be generated. The Code is as follows:

 

/// <Summary>

/// Encrypt the random number generator to generate random Seeds

/// </Summary>

/// <Returns> </returns>

Private Static int chaos_getrandomseed ()

{

Byte [] bytes = new byte [4];

System. Security. cryptography. rngcryptoserviceprovider RNG = new system. Security. cryptography. rngcryptoserviceprovider ();

RNG. getbytes (bytes );

Return bitconverter. toint32 (bytes, 0 );

}

When a random number is generated, each time the random number seed is initialized as a parameter, the Code is as follows:

 

// Output ten random numbers in the message box

String strmsg = "";

For (INT I = 0; I <10; I ++)

{

// Use the secret random number generator to generate a seed each time a random number is generated,

// In this way, different random numbers can be generated even in a short period of time.

Random RDM = new random (chaos_getrandomseed ());

 

// Obtain a random number ranging from 10 to 30.

Int irand = RDM. Next (10,300 );

Strmsg + = irand. tostring () + "";

}

MessageBox. Show (strmsg, "random number test ");

The program runs as follows:

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.