[英]copying array from button1 to button2
i'm beginner at c# and programming in total.. so i'm working on this code in school right now, where i have to generate 21 random numbers between 1-21 (you can have duplicates of numbers). 我是c#和编程人员的初学者。.所以我现在正在学校里研究这段代码,在这里我必须生成1-21之间的21个随机数(您可以复制数字)。 i have made the code and it's working sorta... it generates the numbers in listbox1 but it's not the same numbers i get sorted in listbox3.
我已经编写了代码,并且可以正常工作...它在listbox1中生成数字,但与在listbox3中排序的数字不同。
private void button1_Click(object sender, EventArgs e)
{
int[] a = new int[21];
Random tal = new Random();
for (int x = 1; x < a.Length; x++)
{
a[x] = tal.Next(1, 21);
}
for (int x = 1; x < a.Length; x++)
{
listBox1.Items.Add(a[x]);
}
foreach (int i in a)
{
Array.Sort(a);
listBox3.Items.Add(a[i]);
}
int min = a[1];
for (int x = 1; x < a.Length; x++)
if (a[x] < min)
min = a[x];
listBox2.Items.Add(min);
int max = a[20];
for (int x = 1; x > a.Length; x++)
if (a[x] < max)
max = a[x];
listBox2.Items.Add(max);
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
int[] a = new int[21];
Random tal = new Random();
a.Clone();
foreach (int i in a)
{
Array.Sort(a);
listBox3.Items.Add(a[i]);
}
}
}
}
1.Array begin with index 0, so change all your loops to start from 0: 1.数组从索引0开始,因此将所有循环更改为从0开始:
for (int x = 0; x < a.Length; x++)
instead of 代替
for (int x = 1; x < a.Length; x++)
and also int min = a[0];
并且
int min = a[0];
not int min = a[1];
不是
int min = a[1];
2.Sort the array outside the for loop, there is no need to do it over and over: 2.将数组在for循环外排序,不需要一遍又一遍地做:
Array.Sort(a);
foreach (int i in a)
{
listBox3.Items.Add(a[i]);
}
the items must be the same (but different order). 项目必须相同(但顺序不同)。
and also you are cloning a ( a.Clone();
) and actually not assigning it to anything, so its an extra code. 而且您正在克隆(
a.Clone();
),而实际上没有将其分配给任何东西,因此它是一个额外的代码。
Variables have scope . 变量具有作用域 。
What this means for you right now, is that the a
in button1_Click
is not the same as the a
in button3_Click
(not to mention they are assigned to different arrays). 这意味着什么,你现在,就是
a
中button1_Click
不一样的a
在button3_Click
(何况他们被分配到不同的阵列)。
If you need them to be shared, a
should be declared at the class level (ie, not in a method). 如果你需要他们共享,
a
应在类级别声明(即,不是在一个方法)。 Then both methods can use the same variable (just don't re-assign it!). 然后,这两种方法都可以使用相同的变量(只是不要重新分配它!)。
Also: 也:
a.Clone();
doesn't do anything unless you assign the result Sort
in your loop is totally overkill Sort
完全是过分的 Random tal = new Random()
isn't even used in button3_click
Random tal = new Random()
button3_click
甚至没有使用Random tal = new Random()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.