我正在为学校做一个小任务,我遇到了一些麻烦.该程序的目的是总结2个随机数的滚动36000次.数字应该在1-6的范围内(模拟骰子).
然后我们计算每个求和值的频率并将其显示到控制台.
看起来很容易,除了我在运行程序时得到一个不寻常的输出.当我在调试中运行程序时它工作正常所以我有点难过如何找到问题...
我正在使用一组计数器来计算值被滚动的次数.我得到的输出看起来像这样:5888 0 6045 0 6052 0 5969 0 6010 0 6036(每个值都在换行符上我只是这样输入以节省空间)
当我运行调试(F11)然后在单步执行后按F5时,我得到所需的输出:
973 2022 3044 3990 4984 6061 4997 4030 2977 1954 968
using System;
public class DiceRollUI
{
public static void Main(string[] args)
{
DiceRoll rollDice = new DiceRoll();
Random dice1 = new Random(); //dice 1
Random dice2 = new Random(); //dice 2
int len = 36000;
while( len > 0) {
rollDice.DiceRange((uint)dice1.Next(1, 7) +
(uint)dice2.Next(1,7)); //sum the dice and pass value to array
--len;
}
rollDice.DisplayRange(); //display contents of counter array
Console.ReadLine();
}//end Main method
}//end class DiceRollUI
using System;
public class DiceRoll
{
private uint[] rolledDice = new uint[11]; //counter array to count number of rolls
public void DiceRange(uint diceValue)
{
++rolledDice[diceValue - 2]; //offset values to place in correct element
}//end method DiceRange
public void DisplayRange()
{
for(int i = 0; i < rolledDice.Length; i++)
Console.WriteLine("{0}", rolledDice[i]);
}//end method DisplayRange
}//end class RollDice
Run Code Online (Sandbox Code Playgroud)
这是因为Random()构造函数的工作方式.基于MSDN:
默认情况下,Random类的无参数构造函数使用系统时钟生成其种子值,而其参数化构造函数可以根据当前时间中的滴答数采用Int32值.但是,由于时钟具有有限的分辨率,因此使用无参数构造函数以紧密连续的方式创建不同的随机对象会创建随机数生成器,从而生成相同的随机数序列.
所以你的两个实例Random每次都会生成相同的数字.
其中一个问题是只使用Random两个骰子卷的一个实例,因为你真的不需要其中的两个.
Random dice = new Random();
int len = 36000;
while (len > 0)
{
rollDice.DiceRange((uint) dice.Next(1, 7) +
(uint) dice.Next(1, 7)); //sum the dice and pass value to array
--len;
}
Run Code Online (Sandbox Code Playgroud)