1

我目前正在生成一个随机数(1-20)并计算每个数字随机生成的次数。在textBox1我选择我想要生成的数字数量。我在多行中显示最终结果textBox2。我遇到的问题是,每次我再次单击按钮时,它都会重置随机生成数字的次数。

有没有我可以点击按钮x次并计算一个数字随机生成的次数而不重置计数?我正在尝试在数组的帮助下专门解决这个问题。

代码

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Random r = new Random();

        private void button1_Click(object sender, EventArgs e)
        {


            var n = int.Parse(this.textBox1.Text);



            var y =
                Enumerable
                    .Range(0, n)
                    .Select(x => r.Next(20) + 1)
                    .ToArray();

            var sum = y.Sum();
            var avg = (double)sum / (double)n;
            var frequency = y.ToLookup(x => x);

            textBox2.Text = String.Join(Environment.NewLine, new[]
        {
            "Number of times an integer was randomly generated",
            String.Format("{0} {1}", sum, avg),
        }.Concat(Enumerable
                .Range(1, 20)
                .Select(x => String.Format("{0} ({1})", x, frequency[x].Count()))));

        }

    }
4

2 回答 2

3

变量的范围仅存在于button1_Click方法内部。您需要将其作为私有类变量移出,以便在单击时保持它。它需要对您的代码进行一些小的重构才能到达那里。

public partial class Form1 : Form
{
    private Random r = new Random();

    private int[] counts = new int[20];

    private static string newLine = Environment.NewLine;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int n = 0;
        if (int.TryParse(this.textBox1.Text, out n))
        {
            // Clear the box
            this.textBox2.Text = string.Empty;

            var generatedList = new int[n];
            for (int i = 0; i < n; i++)
            {
                // Upper bound is EXCLUSIVE
                var gen = r.Next(1, 21);
                counts[gen - 1]++;
                generatedList[i] = gen;
            }

            this.textBox2.Text += PrintNumbers(generatedList);
            this.textBox2.Text += PrintCounts(this.counts);
        }
        else
        {
            this.textBox2.Text = "Invalid input! Cannot generate numbers.";
        }
    }

    private static string PrintNumbers(int[] numbers)
    {
        if (numbers == null)
        {
            return "No numbers generated" + newLine;
        }

        string result = "Generated sequence: {";
        for (int i = 0; i < numbers.Length; i++)
        {
            result += numbers[i];

            if (i < numbers.Length - 1)
            {
                result += ", ";
            }
        }

        return result + "}" + newLine;
    }

    private static string PrintCounts(int[] counts)
    {
        if (counts == null)
        {
            return string.Empty;
        }

        string result = string.Empty;
        for (int i = 0; i < counts.Length; i++)
        {
            result += "Number " + (i + 1) + " generated " + counts[i] + " times." + newLine;
        }

        return result;
    }
}

请注意,该方法的上限rand.next(min,max)是独占的,这意味着要生成从 1 到 20 的数字,您需要将其传递 1 到 21。不知道为什么会出现不一致——这有点令人困惑。

n = 10 的输出

Generated sequence: {12, 5, 12, 15, 8, 20, 6, 5, 16, 6}
Number 1 generated 0 times.
Number 2 generated 0 times.
Number 3 generated 0 times.
Number 4 generated 0 times.
Number 5 generated 2 times.
Number 6 generated 2 times.
Number 7 generated 0 times.
Number 8 generated 1 times.    
Number 9 generated 0 times.
Number 10 generated 0 times.
Number 11 generated 0 times.
Number 12 generated 2 times.
Number 13 generated 0 times.
Number 14 generated 0 times.
Number 15 generated 1 times.
Number 16 generated 1 times.
Number 17 generated 0 times.
Number 18 generated 0 times.
Number 19 generated 0 times.
Number 20 generated 1 times.
于 2012-09-14T13:22:31.980 回答
1

您需要记住实例字段中的一些数据。之前在列表中生成的所有数字(这将引入很少的代码更改)或直方图本身作为Dictionary<int, int>.

当局部变量丢失时,实例字段在对事件处理程序的调用中被保留。

于 2012-09-14T13:21:12.443 回答