在for循环之前实例化和在for循环中实例化之间的区别

时间:2015-07-19 13:51:13

标签: c# instantiation

所以我刚刚开始学习C#而且我遇到了这个练习,它掷了一个N次,然后打印每一侧的滚动次数。然而,我得到了答案,我的问题在于在循环之前和循环中实例化Random数字对象。

我的代码是这样的(这是循环之前的实例化):

static void DiceRoll(int RollTimes)
    {

        int roll = 0;

        int counter1 = 0;
        int counter2 = 0;
        int counter3 = 0;
        int counter4 = 0;
        int counter5 = 0;
        int counter6 = 0;

        Random rnd = new Random();

        for (int ctr = 0; ctr < RollTimes; ctr++)
        {
            roll = 0;
            roll = (int)rnd.Next(1, 7);

            switch (roll)
            {
                case 1:
                    counter1++;
                    break;

                case 2:
                    counter2++;
                    break;

                case 3:
                    counter3++;
                    break;

                case 4:
                    counter4++;
                    break;

                case 5:
                    counter5++;
                    break;

                case 6:
                    counter6++;
                    break;
            }
        }

        Console.WriteLine("1 is rolled {0} times.", counter1);
        Console.WriteLine("2 is rolled {0} times.", counter2);
        Console.WriteLine("3 is rolled {0} times.", counter3);
        Console.WriteLine("4 is rolled {0} times.", counter4);
        Console.WriteLine("5 is rolled {0} times.", counter5);
        Console.WriteLine("6 is rolled {0} times.", counter6);
    }

结果是这样的:

1 is rolled A times.
2 is rolled B times.
3 is rolled C times.
4 is rolled D times.
5 is rolled E times.
6 is rolled F times.

在我做对了之前,实例化行(Random rnd = new Random();)在循环中。

for (int ctr = 0; ctr < RollTimes; ctr++)
        {
            roll = 0;
            roll = (int)rnd.Next(1, 7);
            Random rnd = new Random();
            // rest of the code

然后结果(随机):

1 is rolled (N) times.
2 is rolled (N) times.
3 is rolled (N) times.
4 is rolled (N) times.
5 is rolled (N) times.
6 is rolled (N) times.

有人可以解释或启发我为什么实例化的位置会改变结果吗?谢谢!

1 个答案:

答案 0 :(得分:0)

意思是随机对象实际上不是&#34;随机&#34;说实话,除了量子力学之外,现实中没有这样的事情。好的,回到你的问题,为了让你感到满意,在幕后有一系列(非常复杂的),对于给定的起始值(默认值为零),下一个值是计算机,通过内部抓取下一个系列值。内部系列的复杂性让您感觉价值实际上是随机的。每当使用相同的种子实例化新的Random对象时,您将具有相同的系列值。最好的模式是使用重载的构造函数,该构造函数接受种子并使用种子值,使用石灰Datetime.Now.Ticks并尝试缓存随机对象。

所以答案是在循环外部创建一个实例,甚至更好地为每个实例化使用不同的种子。