Mat*_*att 5 c# debugging logic dice
好的,我有一个骰子扔应用程序...
当我逐步执行代码时,它正常运行,'结果'包含正确的投掷结果数,并且它们看起来是随机的,当我让代码运行并完全相同的事情它产生一组相同的数字.
我确信这是一个逻辑错误,我看不到,但摆弄它好几个小时并没有改善情况,所以任何帮助都很有帮助.:)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
lep*_*pie 12
第一个错误:永远不要使用Random的多个实例,使用单个实例,并将其与其他参数一起传递.
当你创建"Random rnd = new Random();"时 它是按当前时间播种的.当您调试代码(需要时间)时,每次都会以不同的方式播种.
创建1个Random实例,并在任何地方引用它.
| 归档时间: |
|
| 查看次数: |
1036 次 |
| 最近记录: |