定义随机数:产生1到9之间的数字-->
Random ran=new Random();
int RNum=ran.Next(1,10);
范例1:针对键盘随机数的产生-->
private static char[] keyPressNum =
{
'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
};
public static string GenerateRandomNumber(int Length)
{
System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
Random rd = new Random();
for (int i = 0; i < Length; i++)
{
newRandom.Append(keyPressNum[rd.Next(62)]);
}
return newRandom.ToString();
}
范例2:定义一数组,并产生不重复的随机数-->
public int[] getRandomNum(int num, int minValue, int maxValue)
{
Random ra = new Random();
int[] arrNum = new int[num];
int tmp = 0;
for (int i = 0; i < num ; i++)
{
tmp = ra.Next(minValue, maxValue); //随机取数
arrNum[i] = getNum(arrNum, tmp, minValue, maxValue, ra); //取出值赋到数组中
}
return arrNum;
}
public int getNum(int[] arrNum, int tmp, int minValue, int maxValue, Random ra)
{
int n = 0;
while (n < arrNum.Length)
{
if (arrNum[n] == tmp) //利用循环判断是否有重复
{
tmp = ra.Next(minValue, maxValue); //重新随机获取。
getNum(arrNum, tmp, minValue, maxValue, ra);//递归:如果取出来的数字和已取得的数字有重复就重新随机获取。
}
n;
}
return tmp;
}