C# 制作一个随机整数数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8870193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making an array of random ints
提问by Dante1986
What i try to to, is generate an array of random int values, where the random values are taken between a min and a max.
我试图生成一个随机 int 值数组,其中随机值在最小值和最大值之间取值。
So far i came up with this code:
到目前为止,我想出了这个代码:
int Min = 0;
int Max = 20;
int[] test2 = new int[5];
Random randNum = new Random();
foreach (int value in test2)
{
randNum.Next(Min, Max);
}
But its not fully working yet. I think i might be missing just 1 line or something. Can anyone help me out pushing me in the right direction ?
但它还没有完全工作。我想我可能只缺少 1 行或其他内容。谁能帮我把我推向正确的方向?
采纳答案by Darin Dimitrov
You are never assigning the values inside the test2array. You have declared it but all the values will be 0. Here's how you could assign a random integer in the specified interval for each element of the array:
您永远不会在test2数组内分配值。您已经声明了它,但所有值都将为 0。以下是您如何在指定的间隔内为数组的每个元素分配一个随机整数:
int Min = 0;
int Max = 20;
// this declares an integer array with 5 elements
// and initializes all of them to their default value
// which is zero
int[] test2 = new int[5];
Random randNum = new Random();
for (int i = 0; i < test2.Length; i++)
{
test2[i] = randNum.Next(Min, Max);
}
alternatively you could use LINQ:
或者,您可以使用 LINQ:
int Min = 0;
int Max = 20;
Random randNum = new Random();
int[] test2 = Enumerable
.Repeat(0, 5)
.Select(i => randNum.Next(Min, Max))
.ToArray();
回答by stephen776
You need to assign the random.next result to the currrent index of your array within the loop
您需要将 random.next 结果分配给循环内数组的当前索引

