.net c#数组问题 声明一个100大小的数组 随机插入1-100之间的数,不能重复

声明一个100大小的数组 随机插入1-100之间的数,不能重复 用c#实现
2024-12-25 04:05:53
推荐回答(2个)
回答1:

int[] intArr = new int[100];
ArrayList myList = new ArrayList();
Random rnd = new Random();
while (myList.Count < 100)
{
int num = rnd.Next(1, 101);
if (!myList.Contains(num))
myList.Add(num);
}
for (int i = 0; i <100; i++)
{
intArr[i] = (int)myList[i];
Console.Write("{0} ", intArr[i]);
Console.WriteLine();
}

回答2:

using System;
using System.Data;
using System.Text;

namespace test{
public class test{
public static void Main(){
int num = 10;//把这个改成100就可以了
StringBuilder insertOk = new StringBuilder();//用于保存已经插入过的数据
System.Random rd = new Random();
int[] arrInt = new int[num];
for(int i=0;i int tmp = rd.Next(1, num+1);
if(insertOk.ToString().IndexOf("," + tmp.ToString() + ",") < 0)
{
insertOk.Append("," + tmp.ToString() + ",");
arrInt[i] = tmp;
i++;
Console.WriteLine(tmp);
}
}
Console.WriteLine(insertOk.ToString());

}
}
}