C# Random.Next - never returns the upper bound?

╄→гoц情女王★ 提交于 2020-01-09 03:07:24

问题


random.Next(0,5)

It never returns the 5 (but sometimes returns the 0.) Why? I thought these are just boundary values that can be returned. Thanks


回答1:


The maxValue for the upper-bound in the Next() method is exclusive—the range includes minValue, maxValue-1, and all numbers in between.




回答2:


The documentation says the upper bound is exclusive. Exclusive means that it is not included in the possible return set. In a more mathematical notation 0 <= x < 5 in this case.




回答3:


Straight from the documentation:

 Summary:
   Returns a random number within a specified range.

 Parameters:
   minValue:
     The inclusive lower bound of the random number returned.

   maxValue:
     The exclusive upper bound of the random number returned. maxValue must be
     greater than or equal to minValue.

 Returns:
     A 32-bit signed integer greater than or equal to minValue and less than maxValue;
     that is, the range of return values includes minValue but not maxValue. If
     minValue equals maxValue, minValue is returned.

If you look at the parameters, you will see that minValue is inclusive (which is why your 0 occurs) and maxValue is exclusive (your 5 never occurs).




回答4:


Good way to remember it is to consider max as amount of numbers from which it takes random number. So random.Next(0,2) means that it takes random out of 2 numbers starting from 0: 0 and 1.




回答5:


This has been written a long time ago but I will comment anyway. I think the main reason for that design decision is that most if not all random number generator at their core generate numbers from 0 to 2^32-1. So if you specify Int32.MaxValue you will never get that number. Having an exception for one number must have been not acceptable to the designers so they decided to have the bracket exclusive. Problem solved!




回答6:


When you just look in Google for "c# random" and follow the first links to the method of desire you get here: http://msdn.microsoft.com/en-us/library/aa329893(v=vs.71).aspx

And there is no hint about the exclusiveness of the upper bound. They must have found the mistake in the code and corrected it with documentation.

So it is important to always check the version of the framework when looking at the documentation. Even when working with old versions of the framework, it is worth to have a look at the newer documentation.



来源:https://stackoverflow.com/questions/5063269/c-sharp-random-next-never-returns-the-upper-bound

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!