我需要创建随机数,但标签中的数字不是随机的2是随机的,但所有的总和是相同的:
这是我的代码
int input = int.Parse(txt1.Text);
if (input <= 6)
{
int Getal1 = 0;
int Getal2 = 0;
Random generator = new Random();
for (int x = 0; x < 11; x++)
{
Getal1 = generator.Next(input) + 1;
Getal2 = generator.Next(input) + 1;
Getal1.ToString();
Getal2.ToString();
}
//int Getal2 = generator.Next(input) + 1;
//int Getal3 = generator.Next(input) + 1;
//int Getal4 = generator.Next(input) + 1;
//int Getal5 = generator.Next(input) + 1;
//int Getal6 = generator.Next(input) + 1;
//int Getal7 = generator.Next(input) + 1;
//int Getal8 = generator.Next(input) + 1;
//int Getal9 = generator.Next(input) + 1;
//int Getal10 = generator.Next(input) + 1;
lbl1.Text = Getal1.ToString();
lbl2.Text = Getal2.ToString();
lbl3.Text = Getal1.ToString();
lbl4.Text = Getal2.ToString();
lbl5.Text = Getal1.ToString();
lbl6.Text = Getal2.ToString();
lbl7.Text = Getal1.ToString();
lbl8.Text = Getal2.ToString();
lbl9.Text = Getal1.ToString();
lbl10.Text = Getal2.ToString();
当我删除循环并撤消评论时,它确实有效。但是这就是代码,我认为我可以做得更小。
答案 0 :(得分:4)
您应该将Random generator = new Random();
和所有变量声明移到循环之外。您还可以将所有标签放入数组中,这样就不必单独分配每个标签。此外,您已将标签的文本仅分配给最新的Getal1, Getal2
值。这就是为什么只有所有其他对与第一对相同的值。
int input = int.Parse(txt1.Text);
if (input <= 6)
{
Random generator = new Random();
Label[] labels = new [] {
lbl1,
lbl2,
lbl3,
lbl4,
lbl5,
lbl6,
lbl7,
lbl8,
lbl9,
lbl10
};
for (int x = 0; x < labels.Length; x++)
{
labels[x].Text = (generator.Next(1, input)).ToString();
}
error.Text = "";
pnl1.Visible = true;
}
默认的Random
构造函数将随机种子初始化为基于当前时间的值。
答案 1 :(得分:0)
int input = int.Parse(txt1.Text);
Random r = new Random();
List<int> sums = new List<int>();
if(input<=8)
{
for (int i = 0; i <= 10; i++)
{
sums.Add( r.Next(input)+ r.Next(input));
}
lbl1.Text = sums[0].ToString();
}