谢谢
public partial class Form1 : Form { public Form1() { InitializeComponent(); go(); } void go() { int[] numbers = new int[8]; foreach (int number in numbers) { numbers[number] = getRandomNumber(); } label1.Text = numbers[0].ToString(); label2.Text = numbers[1].ToString(); label3.Text = numbers[2].ToString(); label4.Text = numbers[3].ToString(); label5.Text = numbers[4].ToString(); label6.Text = numbers[5].ToString(); label7.Text = numbers[6].ToString(); label8.Text = numbers[7].ToString(); } int getRandomNumber() { Random random = new Random(); return random.Next(10,1000); } }
解决方法
only the first label is having a number set
这样做的原因是你以这种方式声明和初始化了一个int []:
int[] numbers = new int[8];
在此之后,您有一个长度为8的数组,但所有的int都是默认值(int),即0.
因此以下的foreach循环……
foreach (int number in numbers) { numbers[number] = getRandomNumber(); }
…只会将第一个int初始化为一个随机数(好吧,不是真正随机的,稍后会更多关于此).您可以使用for循环:
for (int iii=0; iii<numbers.Length;iii++) { numbers[iii] = getRandomNumber(); }
在循环中使用相同的随机实例.否则它会创建相同的数字,因为它是以当前时间播种的.
MSDN:
The random number generation starts from a seed value. If the same
seed is used repeatedly,the same series of numbers is generated. One
way to produce different sequences is to make the seed value
time-dependent,thereby producing a different series with each new
instance of Random. By default,the parameterless constructor of the
Random class uses the system clock to generate its seed value,while
its parameterized constructor can take an Int32 value based on the
number of ticks in the current time.
Random rnd = new Random(); foreach (int number in numbers) { numbers[number] = rnd.Next(10,1000); }
Random random = new Random(); var labels = new[] { label1,label2,label3,label4,label5,label6,label7,label8 }; for (int i = 0; i < labels.Length; i++) { labels[i].Text = random.Next(10,1000).ToString(); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。