The Code is as follows:
Copy codeThe Code is as follows:
Namespace RandomTest
{
Class Program
{
Static void Main (string [] args)
{
For (int I = 0; I <100; I ++)
{
Random d = new Random ();
Console. WriteLine (d. Next (100 ));
}
}
}
}
Theoretically, this program will generate 100 different 0 ~ The value is an integer of 100. In reality, except for the first digit, the remaining 99 digits will generate a random 99 identical digits! Adding a debugging point in the middle or using MessageBox. show () can correctly obtain 100 different random numbers!
Why? Do you want to pause it all at once? Modify the Code:
Copy codeThe Code is as follows:
Namespace RandomTest
{
Class Program
{
Static void Main (string [] args)
{
For (int I = 0; I <100; I ++)
{
Random d = new Random ();
Thread. Sleep (15 );
Console. WriteLine (d. Next (100 ));
}
}
}
}
After re-running, the output number is finally random, and the pause will be normal for more than 15 milliseconds. If only one millisecond is paused, 5-6 random numbers in a row will appear regularly, if it is changed to 5 ms pause, the probability of repeating the same random number is changed to 2-3!
I searched the internet for two days, but it was not helpful. However, on the CSDN Forum, someone quickly gave me a solution:
Copy codeThe Code is as follows:
Namespace RandomTest
{
Class Program
{
Static void Main (string [] args)
{
Random d = new Random ();
For (int I = 0; I <100; I ++)
{
Console. WriteLine (d. Next (100 ));
}
}
}
}
Putting random objects out of the loop can solve the problem! But no one can give an explanation. It is estimated that due to the pseudo-random number, each time a random seed is generated, there will be time for participation, so we will generate a completely consistent "pseudo-random number" in a short time!
Moreover, we can see a seed generation method on the Internet to increase the probability of non-repetition of random numbers.
Copy codeThe Code is as follows:
Static int GetRandomSeed ()
{
Byte [] bytes = new byte [4];
System. Security. Cryptography. RNGCryptoServiceProvider rng = new System. Security. Cryptography. RNGCryptoServiceProvider ();
Rng. GetBytes (bytes );
Return BitConverter. ToInt32 (bytes, 0 );
}
Random random = new Random (GetRandomSeed ());