【发布时间】:2014-09-16 00:47:15
【问题描述】:
编程新手 我想编写一个函数,它返回一个包含 1000 个元素的整数数组,其中包含随机顺序的值 1 到 1000。
private static void RandomNum()
{
//Initialize an array
int[] randomList = new int[1000];
//Initialize an instance of random class
Random rnd = new Random();
// integer variable
int counter = 0;
while (counter < 1000)
{
//store random num
int random = rnd.Next(1, 1001);
if (Array.IndexOf(randomList, random) <= 0)
{
//store random number into Array
randomList[counter] = random;
counter++;
}
}
//output elements in Array
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(randomList[i]);
}
//output number of elements in Array
Console.WriteLine(counter);
Console.Read();
}
任何帮助将不胜感激。
【问题讨论】:
-
Array.IndexOf(randomList, random) <= 0似乎是一个错误,因为它包含零,这是一个有效的索引(第一个)。如果代码旨在避免重复,它将在所有等于第一个的随机数上失败。相反,您可以使用< 0或!randomList.Contains(random)。 -
@TimSchmelter 不错的收获。使用数组而不是列表是否有原因?如果使用列表,您可以这样做 List.Contains(random) 并避免重复。
-
@PWilliams0530:你仍然可以使用
Enumerable.Contains(如评论)。我不知道他为什么需要一个数组,但因为他想要 1000 个随机数,所以大小是已知的,而且数组似乎是合适的。 -
不确定海报的技能水平在哪里(因为他们说他们是编程新手) - 但请查看:stackoverflow.com/questions/5561742/…
标签: .net arrays function random integer