制作一个随机整数数组 [英] Making an array of random ints
问题描述
我尝试的是生成一个随机 int 值数组,其中随机值取自最小值和最大值之间.
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.
到目前为止,我想出了这个代码:
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);
}
但它还没有完全工作.我想我可能只缺少 1 行或其他内容.谁能帮我把我推向正确的方向?
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 ?
推荐答案
您永远不会在 test2
数组中分配值.您已经声明了它,但所有值都将为 0.以下是如何为数组的每个元素在指定的间隔内分配一个随机整数:
You are never assigning the values inside the test2
array. 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:
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);
}
或者你可以使用 LINQ:
alternatively you could use LINQ:
int Min = 0;
int Max = 20;
Random randNum = new Random();
int[] test2 = Enumerable
.Repeat(0, 5)
.Select(i => randNum.Next(Min, Max))
.ToArray();
这篇关于制作一个随机整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!