简体   繁体   English

C#代码仅在步骤中给出预期结果?

[英]C# code only gives expected results on step through?

Ok so I have a dice throw app... 好的,我有一个骰子扔应用程序...

When I step through the code it functions normally and 'results' contains the correct number of throw results and they appear to be random, when I leave the code to run and do exactly the same thing it produces a set of identical numbers. 当我单步执行代码时,它正常运行,'结果'包含正确的投掷结果数,并且它们看起来是随机的,当我让代码运行并完全相同的事情它产生一组相同的数字。

I'm sure this is a logical error I cannot see but fiddling with it for hours hasnt improved the situation, so any help is much appriciated. 我确信这是一个逻辑错误,我看不到,但摆弄它好几个小时并没有改善情况,所以任何帮助都很有帮助。 :) :)

    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的多个实例,使用单个实例,并将其与其他参数一起传递。

When you create "Random rnd = new Random();" 当你创建“Random rnd = new Random();”时 it is seeded by the current time. 它是按当前时间播种的。 When you debug your code (which takes time) it will be seeded differently each time. 当您调试代码(需要时间)时,每次都会以不同的方式播种。

Create 1 instance of Random, and reference that everywhere. 创建1个Random实例,并在任何地方引用它。

You're creating a random class every time you need to create a number. 每次需要创建数字时,您都会创建一个随机类。 Doing this will give you the nutty results. 这样做会给你带来坚果的结果。

See here: FROM MSDN 请参见此处: FROM MSDN

This problem can be avoided by creating a single Random object rather than multiple ones. 通过创建单个Random对象而不是多个Random对象可以避免此问题。

To improve performance, create one Random object to generate many random numbers over time, instead of repeatedly creating a new Random objects to generate one random number. 要提高性能,请创建一个Random对象以随时间生成许多随机数,而不是重复创建新的Random对象以生成一个随机数。

Eg create a private instance of Random... 例如,创建一个随机的私有实例...

In addition to what has been mentioned before... 除了之前提到的......

Use Random for things like dice, card games, choosing random images and so forth. 使用随机的东西,如骰子,纸牌游戏,选择随机图像等。 If you ever need to create a random number for security sake, use System.Security.Cryptography.RandomNumberGenerator. 如果出于安全考虑需要创建随机数,请使用System.Security.Cryptography.RandomNumberGenerator。 This simple example shows creating a random integer. 这个简单的例子显示了创建随机整数。

        RandomNumberGenerator gen = RandomNumberGenerator.Create();
        byte[] myBytes = new byte[4];
        gen.GetBytes(myBytes);
        int myValue = (BitConverter.ToInt32(myBytes, 0));

DO NOT use this unless you have a security need. 除非您有安全需要,否则请勿使用此功能。 The performance is less than that of the Random class. 性能低于Random类的性能。 I suppose you could use this to seed Random but that might be overkill. 我想你可以用它来种子随机,但这可能是矫枉过正的。

EDIT: It occurred to me that I had never tested this. 编辑:我突然想到我从未测试过这个。 A quick performance test showed the following: 快速性能测试显示以下内容:

1,000,000 random numbers: RandomNumberGenerator: 2.6 seconds Random: .015 seconds. 1,000,000随机数:RandomNumberGenerator:2.6秒随机:.015秒。

So Random is about 150 times faster. 所以随机性大约快150倍。

Give the constructor Random a seed. 给构造函数Random一个种子。 That's the problem. 那就是问题所在。

http://msdn.microsoft.com/en-us/library/aa329890%28VS.71%29.aspx http://msdn.microsoft.com/en-us/library/aa329890%28VS.71%29.aspx

Random r = new Random(DateTime.Now.Millisecond);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM