2 × 10个随机生成的数字具有相同的和c#

本文关键字:数字 随机 10个 | 更新日期: 2023-09-27 18:12:40

我有2个列表框,我需要把10个随机生成的数字。然后我需要计算listbox 1和listbox 2的总和,并比较它们,看哪个更大。我确实在每个列表框中得到不同的数字,但由于某种原因,列表框的总和总是相同的。我如何使它的总和是不同的每个列表框。这是我现在的代码。

 private void btnGo_Click(object sender, EventArgs e)
    {
        Random random = new Random();
        listBox1.Items.Clear();
        listBox2.Items.Clear();

        for (int i = 0; i < 10; i++)
        {
            int nummer = random.Next(20);
            int nummer2 = random.Next(20);
            listBox1.Items.Add(nummer);
            listBox2.Items.Add(nummer2);
        }


        if (addListbox1() > addListbox2())
        {
            textBox1.Text = "Listbox1 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox1());
            listBox1.BackColor = Color.Green;
            listBox2.BackColor = Color.Red;

        }
        else
        {
            textBox1.Text = "Listbox2 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox2());
            listBox1.BackColor = Color.Red;
            listBox2.BackColor = Color.Green;

        }

    }
    private int addListbox1()
    {
        int listbox1total = 0;
        for (int k = 0; k < listBox1.Items.Count;)
        {
            listbox1total += Convert.ToInt32(listBox1.Items[k++]);
        }
        return listbox1total;
    }
    private int addListbox2()
    {
        int listbox2total = 0;
        int k = 0;
        while(k < listBox2.Items.Count)
        {
            listbox2total += Convert.ToInt32(listBox1.Items[k++]);
        }
        return listbox2total;
    }

2 × 10个随机生成的数字具有相同的和c#

你在代码中有一个打字错误(一个关于copy + paste的老故事):

listbox2total += Convert.ToInt32(listBox1.Items[k++]);

应为

// please, notice "listBox2.Items"
listbox2total += Convert.ToInt32(listBox2.Items[k++]);

listbox2total应该是listBox2.Items的和

为了避免这类错误,改变设计,不要自己复制,提取方法:

// Easiest, but not thread safe
private static Random random = new Random();
private static void FillBox(ListBox box, int count = 10) {
  box.Items.Clear();
  box.Items.AddRange(Enumerable
    .Range(0, count)
    .Select(x => (Object) random.Next(20))
    .ToArray());
}
private static int SumBox(ListBox box) {
  return box.Items
    .OfType<Object>()
    .Sum(x => Convert.ToInt32(x));
}
...
FillBox(listBox1);
FillBox(listBox2);
if (SumBox(listBox1) > SumBox(listBox2)) {
  ...
}