C#中生成中国福利彩票36选7中7个不重复整数

本人简单做了一个,但是运行总是CPU100%,没法生成整数。。。

System.Random ran = new Random();
int[] arry=new int[7];
for (int i = 0; i <arry.Length; i++)
{
where: arry[i]=(int)ran.Next(0,36)+1;
for (int j = 0; j <= i;j++ )
{
if (arry[i] == arry[j])
goto where;
}

}
textBox1.Text=arry[1]+"";
textBox2.Text = arry[2] + "";
textBox6.Text = arry[3] + "";
textBox4.Text = arry[4] + "";
textBox5.Text = arry[5] + "";
textBox6.Text = arry[6] + "";
textBox7.Text = arry[7] + "";
2楼的生成的有可能是重复的,36选7不能有重复的。

我这程序只用循环7次而已,就可以完成了
static void Main(string[] args)
{
int[] number = new int[36];///36个数

int[] newNumber = new int[7];///选出的7个数

int i,maxIndex = 35;

for (i = 0; i < 36; i++)///初始化0~35个数
{
number[i] = i;
}

Random rand = new Random();

for (i = 0; i < 7; i++)
{
///随机产生0~35之间的数作为下标
int index = rand.Next(0, maxIndex);
///把产生的下标里的值给新的数组
newNumber[i] = number[index];
///把产生下标的值和第maxIndex个值交换
int tmp = number[index];

number[index] = number[maxIndex];

number[maxIndex] = tmp;

maxIndex--;///自减1,避免下次产生的下标会重复
}

for (i = 0; i < 7; i++)///输出这7个选出的数
{
Console.Write("{0} ", newNumber[i]);
}
Console.Read();
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-06-25
private void btnOk_Click_1(object sender, EventArgs e)
{

Random r = new Random();

txt1.Text = (int)r.Next(1, 36) + "";
txt2.Text = (int)r.Next(1, 36) + "";
txt3.Text = (int)r.Next(1, 36) + "";
txt4.Text = (int)r.Next(1, 36) + "";
txt5.Text = (int)r.Next(1, 36) + "";
txt6.Text = (int)r.Next(1, 13) + "";
txt7.Text = (int)r.Next(1, 13) + "";
}
第2个回答  2009-06-26
楼主你因为一开始就把随机生成的放到数组里了,所以,当i=j的时候就goto到where那里了,就会地循环。可以改成for (int j = 0; j <i;j++ )

或者:
System.Random ran = new Random();
System.Collections.Generic.List<int> aa = new System.Collections.Generic.List<int>();
for (int i = 0; i <7; i++)
{
int xx=(int)ran.Next(0,36)+1;
bool bb = true;
while(aa.Contains(xx)){xx=(int)ran.Next(0,36)+1;}
aa.Add(xx);

}
textBox1.Text=arry[1]+"";
textBox2.Text = arry[2] + "";
textBox6.Text = arry[3] + "";
textBox4.Text = arry[4] + "";
textBox5.Text = arry[5] + "";
textBox6.Text = arry[6] + "";
textBox7.Text = arry[7] + "";
第3个回答  2009-06-25
改成下面这样就行了
private void button1_Click(object sender, EventArgs e)
{
Random ran = new Random();
List<int> arr = new List<int>();
for (int i = 0; i < 7; i++)
{
arr.Add(ran.Next(0, 36));
for (int j = 0; j < arr.Count - 1; j++)
{
if (arr[i] == arr[j])
{
arr.RemoveAt(i);
i--;
break;
}
}
}
foreach (int var in arr)
{
MessageBox.Show(var.ToString());
}
}
第4个回答  2020-05-13
这个都看不准,你买什么??
相似回答