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) + "
");
}