C# c数组在没有MessageBox的情况下无法初始化
我在c程序中遇到了一个奇怪的问题。该程序的目的是滚动骰子并显示其输出。程序的逻辑很好,只有在我输出到消息框时才合理地工作。以下是代码:C# c数组在没有MessageBox的情况下无法初始化,c#,arrays,winforms,C#,Arrays,Winforms,我在c程序中遇到了一个奇怪的问题。该程序的目的是滚动骰子并显示其输出。程序的逻辑很好,只有在我输出到消息框时才合理地工作。以下是代码: private void btnRoll_Click(object sender, EventArgs e) { lbDice.Items.Clear(); int[] rolls = new int[13]; for (int i = 1; i < numTxt.Value; i++) {
private void btnRoll_Click(object sender, EventArgs e)
{
lbDice.Items.Clear();
int[] rolls = new int[13];
for (int i = 1; i < numTxt.Value; i++) {
int index = new Random().Next(1, 7) + new Random().Next(1, 7);
//MessageBox.Show(index + ""); THIS LINE IS REQUIRED
rolls[index] += 1;
}
updateList(rolls);
}
public void updateList(int[] rolls)
{
for (int i = 1; i < rolls.Length; i++)
{
lbDice.Items.Add("" + i + " " + rolls[i]);
}
}
如果不存在,程序将只向每个索引添加1。无需每次创建一个随机实例。保留并重复使用。 如果创建的新实例在时间上过于接近,它们将产生与随机生成器从系统时钟中播种时相同的随机数序列 下面的代码可能对您有所帮助
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please provide a number and press 'Enter'");
var input = Console.ReadLine();
int lenght;
if (!int.TryParse(input, out lenght))
{
lenght = 10;
}
int l = 13;
int[] rolls = new int[l];
var rnd = new Random();
for (int i = 1; i < lenght; i++)
{
int index = rnd.Next(1, 7) + rnd.Next(1, 7);
//MessageBox.Show(index + ""); THIS LINE IS REQUIRED
rolls[index] += 1;
}
for (int i = 0; i < l; i++)
{
Console.WriteLine($"rolls[{i}] = {rolls[i]}");
}
Console.WriteLine("Done. Prss any key to exit");
Console.ReadKey();
}
}
}
总的来说,我认为这与
祝你好运 根据我的经验,这与Random类如何生成随机数有关。多次执行新的随机操作可以为每个案例创建相同的值 仅尝试创建一次随机类实例:
Random rand = new Random();
for (int i = 1; i < numTxt.Value; i++) {
int index = rand.Next(1, 7) + rand.Next(1, 7);
rolls[index] += 1;
}
作为一个实验,您可以用Sleep替换MessageBox行,看看这是否也有效,如果不将其放入,会发生什么?