好吧,我有掷骰子的应用程序...

当我逐步执行代码时,它正常运行,并且“结果”包含正确数量的throw结果,并且它们看起来是随机的,当我让代码运行并执行完全相同的操作时,它会产生一组相同的数字。

我确定这是一个逻辑错误,我看不到,但经过数小时的摸索并没有改善这种情况,因此,我们非常乐意提供任何帮助。 :)

    class Dice
{

    public int[] Roll(int _throws, int _sides, int _count)
    {
        Random rnd = new Random();
        int[] results = new int[_throws];
        // for each set of dice to throw pass data to calculate method
        for (int i = 0; i < _throws; i++)
        {
            int thisThrow = Calculate(_sides, _count);
            //add each throw to a new index of array... repeat for every throw
            results[i] = thisThrow;
        }

        return results;
    }


    private int Calculate(int _sides, int _count)
    {
        Random rnd = new Random();
        int[] result = new int[_count];
        int total = 0;
        //for each dice to throw put data into result
        for (int i = 0; i < _count; i++)
        {
            result[i] = rnd.Next(1, _sides);
        }
        //count the values in result
        for (int x = 0; x < _count; x++)
        {
            total = total + result[x];
        }
        //return total of all dice to Roll method
        return total;
    }
}

最佳答案

第一个错误:切勿使用Random的多个实例,仅使用一个实例,并将其与其他参数一起传递。

10-05 20:33
查看更多