开发者

Random Function In C#

开发者 https://www.devze.com 2023-01-25 12:13 出处:网络
What is the best way to select a random numbe开发者_开发问答r between two numbers in C#? For instance, if I have a low value of 23 and a high value of 9999, what would the correct code be to select a

What is the best way to select a random numbe开发者_开发问答r between two numbers in C#?

For instance, if I have a low value of 23 and a high value of 9999, what would the correct code be to select a random number between and including these two numbers? Thanks in Advance


Use the Random class like this:

Random rnd = new Random(); 
rnd.Next(23, 10000);

Make sure that you only initialize your rnd object once, to make sure it really generate random values for you.

If you make this loop for instance:

for( int i = 0 ; i < 10; i++ ){
  Random rnd = new Random();
  var temp = rnd.Next(23, 10000);
}

temp will be the same each time, since the same seed is used to generate the rnd object, but like this:

Random rnd = new Random();
for( int i = 0 ; i < 10; i++ ){
  var temp = rnd.Next(23, 10000);
}

It will generate 10 unique random numbers (but of course, by chance, two or more numbers might be equal anyway)


It depends on whether you are looking for an integer or a double. For an integer use Random.Next(minValue, maxValue):

Returns a random number within a specified range.

Note that the minValue is inclusive but the maxValue is exclusive.

There is no equivalent method for choosing a random double within a specified range. Instead you should use the NextDouble method to pick a random number between 0.0 and 1.0 and then use a linear transformation to extend, reduce and/or translate the range.

0

精彩评论

暂无评论...
验证码 换一张
取 消