Why does it appear that my random number generator

2019-01-03 11:12发布

I'm working in Microsoft Visual C# 2008 Express.

I found this snippet of code:

    public static int RandomNumber(int min, int max)
    {
        Random random = new Random();

        return random.Next(min, max);
    }

the problem is that I've run it more than 100 times, and it's ALWAYS giving me the same answer when my min = 0 and max = 1. I get 0 every single time. (I created a test function to run it - really - I'm getting 0 each time). I'm having a hard time believing that's a coincidence... is there something else I can do to examine or test this? (I did re-run the test with min = 0 and max = 10 and the first 50ish times, the result was always "5", the 2nd 50ish times, the result was always "9".

?? I need something a little more consistently random...

-Adeena

标签: c# random
13条回答
倾城 Initia
2楼-- · 2019-01-03 11:24

The min is inclusive, but the max is exclusive. Check out the API

查看更多
太酷不给撩
3楼-- · 2019-01-03 11:24

Several posters have stated that Random() uses a seed based on the current second on the system clock and any other instance of Random created in the same second will have the same seed. This is incorrect. The seed for the parameterless constructor of Random is based on the tick count, or number of milliseconds since boot time. This value is updated on most systems approximately every 15 milliseconds but it can vary depending on hardware and system settings.

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-03 11:27

The problem with min = 0 and max = 1 is that min is inclusive and max is exclusive. So the only possible value for that combination is 0.

查看更多
Viruses.
5楼-- · 2019-01-03 11:27

in VB i always start with the Randomize() function. Just call Randomize() then run your random function. I also do the following:

Function RandomInt(ByVal lower As Integer, ByVal upper As Integer) As Integer
    Return CInt(Int((upper - lower + 1) * Rnd() + lower))
End Function

Hope this helps! :)

查看更多
倾城 Initia
6楼-- · 2019-01-03 11:29

That overload of Next() 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.

0 is the only possible value for it to return. Perhaps you want random.NextDouble(), which will return a double between 0 and 1.

查看更多
再贱就再见
7楼-- · 2019-01-03 11:32
random = new Random();

This initiates random number generator with current time (in sec). When you call your function many times before system clock changed, the random number generator is initiated with the same value so it returns same sequence of values.

查看更多
登录 后发表回答