In C #, the usual big way to generate random numbers is new random (). Next (1,10) and other methods.
But there's a problem with a careful discovery:
Look at the code:
for (int0; i++ ) { Console.WriteLine (new Random (). Next (1)); }
Operation Result:
Finding random numbers is basically the same. There is a problem, every time the random is the same, it is not a random number.
Take a closer look at the constructor of random
PublicRandom (): This(Environment.tickcount) {}/// <summary>Initializes a new instance of the<see cref= "T:System.Random"/>class, using the specified seed value.</summary> /// <param name= "Seed" >a number used to calculate a starting value for the pseudo-random number sequence. If a negative number is specified, the absolute value of the that number is used. </param>[__dynamicallyinvokable] PublicRandom (intSeed) { intnum = (Seed = =-2147483648) ?2147483647: Math.Abs (Seed); intnum2 =161803398-num; This. seedarray[ -] =num2; intNUM3 =1; for(inti =1; I < -; i++) { intNUM4 = +I -; This. SEEDARRAY[NUM4] =num3; NUM3= num2-num3; if(Num3 <0) {num3+=2147483647; } num2= This. SEEDARRAY[NUM4]; } for(intj =1; J <5; J + +) { for(intK =1; K < About; k++) { This. SEEDARRAY[K]-= This. seedarray[1+ (k + -) % -]; if( This. SEEDARRAY[K] <0) { This. Seedarray[k] + =2147483647; } } } This. Inext =0; This. INEXTP = +; Seed=1; }
The parameterless constructor actually calls the argument constructor, passing the default value: environment.tickcount ,
System. environment.tickcount Gets the boot time function.
In other words, each pass in is the same value.
If we change the code, the new Random () argument is passed.
for (int0; i++ ) { Console.WriteLine(new Random (Guid.NewGuid ()). GetHashCode ()). Next (1)); }
The results of this operation:
Obviously not the same. is a random effect.
There is also a way to achieve random effects:
New // generate objects outside for (int0; i++ ) { Console.WriteLine (RND). Next (1// Call the same object to produce a random number. }
Operation Result:
You can also achieve a random effect.
New Random () in C #