如何取得1-100之间的5个不同的随机数,急.....在线等
10 个解决方案
Random rd = new Random();
int n1 = rd.Next(100);
int n2 = rd.Next(100);
.....
int[] rIntArr = new int[5];
Random rdm = new Random();
for (int i = 0; i < rIntArr.Length; i++)
{
rIntArr[i] = rdm.Next(100);
}
可以把生成的随机数放到List中,每次生成的随机数在List中看有没有
List<int> list;
int n1 = rd.Next(100);
list.Add(n1);
int n2 = rd.Next(100);
if(!list.Contains(n2)) list.Add(n2);
public static int[] RandomNumbers(int ACount, int AMinValue, int AMaxValue)
{
if (ACount <= 0) return null;
if (AMaxValue < AMinValue)
AMinValue = AMaxValue | (AMaxValue = AMinValue) & 0;
if (ACount > AMaxValue - AMinValue + 1) return null; // 取的个数多余范围就算了
List<int> vValues = new List<int>();
for (int i = AMinValue; i <= AMaxValue; i++)
vValues.Add(i);
int[] Result = new int[ACount];
Random vRandom = new Random();
for (int i = 0; i < ACount; i++)
{
int j = vRandom.Next(vValues.Count);
Result[i] = vValues[j];
vValues.RemoveAt(j);
}
return Result;
}
private void button1_Click(object sender, EventArgs e)
{
int[] A = RandomNumbers(5, 1, 100);
foreach (int i in A)
Console.WriteLine(i);
}
>Red_angelX(八戒):
>1楼的就可以了 Next产生的不会重复
Random vRandom = new Random();
for (int i = 0; i < 100; i++ )
Console.WriteLine(vRandom.Next(2));
取0、1的随机数,100次Next()不重复??
“Next产生的不会重复”在哪里查到的资料? 难道你用的是 .NET 火星版