int myran = 10;//初始化myran public static int GenForInt(int minvalue, int maxvalue,ref int myran) //自动生成int型的随机数据 { Random ran; int RandKey; do { ran = new Random(unchecked((int)DateTime.Now.Ticks)); RandKey = ran.Next(minvalue, maxvalue); }while (RandKey == myran); Console.WriteLine("RandKey:" + RandKey); myran = RandKey; //将本次的随机值赋给myran return RandKey; }
------解决方案-------------------- Random ra=new Random(unchecked((int)DateTime.Now.Ticks)); int[] arrNum=new int[10]; int tmp=0; int minValue=1; int maxValue=10; for (int i=0;i<10;i++) { tmp=ra.Next(minValue,maxValue); arrNum=getNum(arrNum,tmp,minValue,maxValue,ra); } public int getNum(int[] arrNum,int tmp,int minValue,int maxValue,Random ra) { int n=0; while (n<=arrNum.Length-1) { if (arrNum[n]==tmp) { tmp=ra.Next(minValue,maxValue); getNum(arrNum,tmp,minValue,maxValue,ra); } n++; } return tmp; } 参考http://www.cnblogs.com/happyhippy/archive/2007/04/03/698384.html
------解决方案-------------------- ran = new Random(unchecked((int)DateTime.Now.Ticks)); 放到循环体外
------解决方案-------------------- 如果要输出的随机数不重复,都把生成好了的,放到一个列表中 Random rnd = new Random(); 比如说输出1-100不重复的随机数 List<int> list=new List<int>(); for(int i=0;i<100;i++) { int value=rnd.Next(1, 101); while(list.Contains(value)) { value=rnd.Next(1, 101);