namespace ArrayRandThree{ class Program { static void Main(string[] args) { //实例化Hashtable Hashtable hashtable = new Hashtable(); Random rm = new Random(); int RmNum = 100; for (int i = 0; hashtable.Count < RmNum; i++) { //产生随机数给nValue int nValue = rm.Next(100); if (!hashtable.ContainsValue(nValue) && nValue != 0) { ////增加元素nValue hashtable.Add(nValue, nValue); //value的遍历 foreach (int value in hashtable.Values) { Console.WriteLine(value); } } Console.ReadKey(); } } }}方法3:List 类using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace ArrayRandFour{ class Program { static void Main(string[] args) { List<int> listNum = new List<int>(); Random random = new Random(); //最小随机数 const int Min = 100; //最小随机数 const int Max = 999; //产生多少个随机数,这里是10个 const int Count = 10; for (int i = 0; i < 100; i++) { var num = random.Next(Min, Max); if (!listNum.Contains(num)) { //将产生的随机数num添加到listNum尾部 listNum.Add(num); //判断 达到设定的Count,跳出循环 if (listNum.Count == Count) { break; } } } //遍历 listNum foreach (int k in listNum) { Console.Write("{0} ", k); } Console.ReadKey(); } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)