I am writing a method that will generate an unsigned int between 1 and 6 (boundaries included). The current method I have is below.
private static Random random = new Random();
...
private static uint GetRandomChannel()
{
return Convert.ToUInt32(random.Next(1, 6));
}
I’ve run this method a thousand times and I get numbers 1 through 5 but never get 6. Why is this happening and how can I fix it?
The second parameter to
random.Next()is an exclusive upper bound.This means that
random.Next(1, 6)will only return valuesnin the range1 <= n < 6.So for your die rolling simulation you will need to use
Note: The design of this API is odd. It has special case handling for
minValue == maxValuewhich seems to needlessly complicate the API. If I had designed this API I would have made both parameters be inclusive limits. This would have resulted in a pleasing symmetry and would have allowed random numbers that cover the full range ofint.