【问题标题】:c# array not working initializing without MessageBox [closed]c#数组在没有MessageBox的情况下无法初始化[关闭]
【发布时间】:2017-03-30 18:24:46
【问题描述】:

我在使用 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++) {
            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。

【问题讨论】:

  • 如果你把它放进去会发生什么?

标签: c# arrays winforms


【解决方案1】:

根据我的经验,这与 Random 类如何生成随机数有关。多次执行new Random() 可以为每种情况创建相同的值。

尝试只创建一次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;
}

作为一项实验,您可以将 MessageBox 行替换为 Sleep 并查看是否也有效

【讨论】:

    【解决方案2】:

    无需每次都创建 Random 实例。保留并重复使用它。 如果您创建新实例的时间太接近,它们将产生与随机生成器从系统时钟播种的相同系列的随机数。

    此代码(如下)可能会对您有所帮助。

    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();
            }
        }
    }
    

    总的来说我认为这与this question有关

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多