Paip. C #. Net method to obtain different random numbers cyclically Based on Time

Source: Internet
Author: User

Paip. C #. Net method to obtain different random numbers cyclically Based on Time

Author attilax, email: 1466519819@qq.com

Generally, you can use random Ra = new random ..

However, if the application is in a for loop, multiple random values are basically the same. The reason is as follows:

It is not safe to use the system time for random seeds.ProgramWhen running on a fast computer, the system clock of the computer may not have time to change between calls of the constructor, and the seed values of different random instances.

May be the same

Solution: Add thread. Sleep (1) to the loop body );
----------
In this way, the time in the loop is different. Then, ticks is taken and the last nine digits are taken as seeds for int. To ensure that each seed is different, a random value is recommended ..

Thread. Sleep (1 );
Long tick = datetime. Now. ticks; // a timestamp in 0.1 s, 18 bits
Int seed = int. parse (tick. tostring (). substring (9); // the maximum value of the int type: 2147483647

Complete source code
-------

for (INT I = 0; I <20; I ++)
{< br>
thread. sleep (1);
long tick = datetime. now. ticks; // a timestamp in the unit of 0.1 nanoseconds, 18 bits
int seed = int. parse (tick. tostring (). substring (9); // maximum value of the int type: 2147483647
// or use unchecked (INT) Tick) alternatively, you can
random ran = new random (SEED);

int iresult;
int iup = 100;
int idown = 50;
iresult = ran. next (idown, iup);
response. write (iresult + "

");
response. write (seed. tostring () + "---" + unchecked (INT) Tick) + "

");
}

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.