Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use random.Next method in C #

Shulou Source: shulou.com Published: 2022-06-03 11:01:59 09月25日 Update

This article mainly introduces how to use the random.Next method in C#. It is very detailed and has a certain reference value. Friends who are interested must finish it!

The. Net Random class does a pretty good job of generating random numbers. Note, however, that if you sow with the same number, you will get the same "random" number each time. If you do not want this behavior to provide no seeds. If you are using a random number generator instead of the built-in .NET generator, check out random.org.

Random.Next method in C #

1.random.Next (): returns a non-negative random number

2.random.Next (MaxValue): returns a non-negative random number that is less than the specified maximum (Note: a. Is the upper bound of the random number that is less than the maximum value to generate (the random number cannot take this upper bound value); b.maxValue type: [System..::.Int32], maxValue must be greater than or equal to zero.

3.Random..::.Next (minValue,maxValue): returns a random number within a specified range.

4. Return value type: [System..::.Int32], a 32-bit signed integer greater than or equal to minValue and less than maxValue, that is, the returned value range includes minValue but does not include maxValue. Returns minValue if minValue is equal to maxValue.

Probability of Random.Next ()

I want to write a lottery program, which needs to randomly select 20000 numbers in the range of 1-20000. The code is as follows:

Randomr=NewRandom (seed); / / seedisa6digitse.g123456

Inti=0

While (true) {

R.Next (2000000)

ITunes +

If (I > = 20000)

Break

}

My question is:

Does it ensure the same probability that all numbers range from 1 to 2000000?

Is there an upper limit of 2000000 in r.Next ()?

St

Including the upper limit?

No, the upper limit is exclusive, so you must use 2000001 to include 2000000.

Do you have any suggestions?

Let me venture to advise against the use of while (true) / break. Simply put the condition of if in the while statement:

Randomr=NewRandom (seed); / / seedisa6digitse.g123456

Inti=0

While (iTunes +)

Tags: Random number number generation method Category same upper bound range maximum upper bound content maximum generator article type good bold code value interest Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Huawei MariaDB Docker Apple