嵌套随机生成器不是随机的

时间:2012-08-03 23:18:55

标签: c# asp.net random

我有以下代码。随机的r工作,让我大约10%的if。然而,rr似乎不起作用。它总是返回0.我做错了什么?

我想在10%的时间内随机选择两种选择。这是一个asp.net应用程序。点击按钮即可执行代码。

        Random r = new Random();
        Random rr = new Random();

        int randomnum = r.Next(0, 100);
        if (randomnum <= 10)
        {

            int randompick = rr.Next(0, 2);
            if (randompick == 0)
            {

3 个答案:

答案 0 :(得分:4)

如果您对外环的随机性感到满意,请考虑

int randompick = randomnum % 2;

而不是嵌套的Random对象。

答案 1 :(得分:1)

你可以使用相同的Random对象进行随机选择,对吗?

答案 2 :(得分:0)

如上所述,您应该只使用一个伪随机流并仅将其实例化一次。我按照这些方针构建我的解决方案:

class SomeWidget
{
    private static Random rng ;

    static SomeWidget()
    {
        rng = new Random() ;
        return ;
    }

    public SomeWidget()
    {
        return ;
    }

    public int DoOneThing90PercentOfTheTimeAndSomethingElseTheRestOfTheTime()
    {
        int rc ;
        int n = rng.Next() % 10 ; // get a number in the range 0 - 9 inclusive.
        if ( n != 0  ) // compare to whatever value you wish: 0, 1, 2, 3, 4, 5, 6, 8 or 9. It makes no nevermind
        {
             rc = TheNinetyPercentSolution() ;
        }
        else
        {
            rc = TheTenPercentSolution() ;
        }
        return rc ;
    }

    private int TheTenPercentSolution()
    {
        int rc ;
        int n = rng.Next() % 2 ;
        if ( n == 0 )
        {
            rc = DoOneThing() ;
        }
        else
        {
            rc = DoAnotherThing() ;
        }
        return rc ;
    }

    private int DoOneThing()
    {
        return 1;
    }

    private int DoAnotherThing()
    {
        return 2 ;
    }

    private int TheNinetyPercentSolution()
    {
        return 3 ;
    }

}
相关问题