说明:这段代码使用了递归来检测新取得随机数的唯一性,而递归使用不当很容易造成栈溢出和死循环,所以不建议使用,这里是用以学习研究。
/// <summary>
/// 获取随机数
/// 建立一个form,加入一个richTextBox对像,一个button对像
/// </summary>
public partial class Form1 : Form
{
private int tmp, min=1000, max=10000;
Random random = new Random();
ArrayList alInt = new ArrayList();
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 获取一个随机数,运用递归检测这个随机数时的唯一性,
/// 如果是唯一的,则存入数组
/// </summary>
/// <param name="alistInt"></param>
/// <param name="temp"></param>1
/// <param name="minValue"></param>
/// <param name="maxValue"></param>
/// <param name="ra"></param>
/// <returns></returns>
public int getNum(ArrayList alistInt, int temp, int minValue, int maxValue, Random ra)
{
int n = 0;
while (n < alistInt.Count )
{
if ((int)alistInt[n] == temp)//用循环判断是否有重复
{
temp = ra.Next(minValue, maxValue);//重新获取随机数
temp = getNum(alistInt, temp, min, max, ra);//递归:如果取出来的数字和已取得的数字有重复就重新获取
//break;
}
n++;
}
return temp;
}
private void button1_Click(object sender, EventArgs e)
{
tmp= random.Next(min,max);
tmp= getNum(alInt, tmp, min, max, random);
alInt.Add(tmp);//把新取得随机数存入组
for (int i = 0; i < alInt.Count; i++)
{
richTextBox1.AppendText(alInt[i].ToString() + "*");
}
richTextBox1.AppendText("\r\n新的数据:");
}
}
/// 获取随机数
/// 建立一个form,加入一个richTextBox对像,一个button对像
/// </summary>
public partial class Form1 : Form
{
private int tmp, min=1000, max=10000;
Random random = new Random();
ArrayList alInt = new ArrayList();
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 获取一个随机数,运用递归检测这个随机数时的唯一性,
/// 如果是唯一的,则存入数组
/// </summary>
/// <param name="alistInt"></param>
/// <param name="temp"></param>1
/// <param name="minValue"></param>
/// <param name="maxValue"></param>
/// <param name="ra"></param>
/// <returns></returns>
public int getNum(ArrayList alistInt, int temp, int minValue, int maxValue, Random ra)
{
int n = 0;
while (n < alistInt.Count )
{
if ((int)alistInt[n] == temp)//用循环判断是否有重复
{
temp = ra.Next(minValue, maxValue);//重新获取随机数
temp = getNum(alistInt, temp, min, max, ra);//递归:如果取出来的数字和已取得的数字有重复就重新获取
//break;
}
n++;
}
return temp;
}
private void button1_Click(object sender, EventArgs e)
{
tmp= random.Next(min,max);
tmp= getNum(alInt, tmp, min, max, random);
alInt.Add(tmp);//把新取得随机数存入组
for (int i = 0; i < alInt.Count; i++)
{
richTextBox1.AppendText(alInt[i].ToString() + "*");
}
richTextBox1.AppendText("\r\n新的数据:");
}
}