gpt4 book ai didi

c# - 2 x 10 随机生成的数字具有相同的总和 c#

转载 作者:行者123 更新时间:2023-11-30 21:45:34 25 4
gpt4 key购买 nike

我有 2 个列表框,我需要将 10 个随机生成的数字放入其中。然后我需要计算列表框 1 的总和和列表框 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;
}

最佳答案

您在代码中有一个错字(复制+粘贴的老故事):

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)) {
...
}

关于c# - 2 x 10 随机生成的数字具有相同的总和 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40001169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com