c# 0-100不不重复随机数 乱序填充到100的数组中

2024-12-13 17:34:29
推荐回答(5个)
回答1:

//0-100有101个数,但你只是放到100长度的数组,到时自己修改下
Random rbd = new Random();
ArrayList myarray = new ArrayList();
int[] num = new int[100];
while (myarray.Count <= 100)
{
int next = rbd.Next(0,101);
if (!myarray.Contains(next))
{
myarray.Add(next);
}
}
for (int i = 0; i < 100; i++)
{
num[i] = int.Parse(myarray[i].ToString());
}
for (int i = 0; i < 100; i++)
{
Console.Write(num[i]+" ");
}

Console.ReadKey();
}

希望采纳给分啊 谢谢

回答2:

int[] nums = new int[100];
Random random = new Random();

for (int i = 0; i < 100; i++)
{
nums[i] = i;
}
int pastnum = random.Next(0,100);
if (pastnum != 100) nums[pastnum] = 100;
for (int i = 0; i < 50; i++)
{
int index1 = random.Next(0,99);
int index2 = random.Next(0,99);
int num = nums[index1];
nums[index1] = nums[index2];
nums[index2] = num;
}

回答3:

用数列实现, 随机从中抽取一个数字,然后在该数列中删除
private static int[] disorder(int myLength)
{
int[] myNums = new int[myLength];

System.Collections.ArrayList preNums = new System.Collections.ArrayList();//准备数列
Random random = new Random();
for (int i = 0; i < myLength; i++)
preNums.Add(i); //第i个的值为i
for (int i = myLength; i > 0; i--)
{
int p = random.Next(0, i);
myNums[i-1] = Convert.ToInt32(preNums[p]);
preNums.RemoveAt(p);//移除已经放进数组的数字
}
return myNums;
}

回答4:

接着你的写最后一个循环:
for(int i=0;i {
//如果获取的随机数,等于nums数组就返回
if(a==nums[i])
{
contion;
}
nums[i]=a;
}

回答5:

private void Init()
{
List intlist = new List();
while (intlist.Count < 100)
{
int a = new Random().Next(0, 100);
if (!intlist.Contains(a))
{
intlist.Add(a);

}
}
}