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

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

52523 次浏览

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

文件说上界是独占的。独占意味着它不包含在可能的返回集中。在这种情况下,在一个更数学符号的 0 <= x < 5

根据文件记录:

 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.

如果查看参数,您将看到 minValue是包含的(这就是为什么出现0) ,而 maxValue是独占的(从不出现5)。

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

而且没有关于上界的排他性的暗示。他们一定是发现了代码中的错误,并用文档进行了纠正。

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.

记住这一点的好方法是把 max 看作是取随机数的数量。 所以 random.Next(0,2)意味着它从0:0和1开始的2个数中随机抽取。

这是很久以前写的,但我还是要评论一下。我认为这个设计决定的主要原因是,大多数(如果不是全部的话)随机数生成器在它们的核心产生从0到2 ^ 32-1的数字。因此,如果指定 Int32.MaxValue,则永远不会得到该数字。对于一个数字有一个例外必须是不能接受的设计者,所以他们决定有括号独占。问题解决了!