Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 生成一个随机整数数组_C#_Arrays_Random_Int - Fatal编程技术网

C# 生成一个随机整数数组

C# 生成一个随机整数数组,c#,arrays,random,int,C#,Arrays,Random,Int,我试图生成一个随机int值数组,其中随机值取最小值和最大值之间的值 到目前为止,我提出了以下代码: int Min = 0; int Max = 20; int[] test2 = new int[5]; Random randNum = new Random(); foreach (int value in test2) { randNum.Next(Min, Max); } 但它还没有完全发挥作用。 我想我可能只漏了一行什么的。 有谁能帮我把我推向正确的方向吗?你从来没有在tes

我试图生成一个随机int值数组,其中随机值取最小值和最大值之间的值

到目前为止,我提出了以下代码:

int Min = 0;
int Max = 20;

int[] test2 = new int[5];
Random randNum = new Random();
foreach (int value in test2)
{
    randNum.Next(Min, Max);
}
但它还没有完全发挥作用。 我想我可能只漏了一行什么的。
有谁能帮我把我推向正确的方向吗?

你从来没有在
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);
}

您需要将random.next结果分配给循环中数组的当前索引

您并不是每次迭代都为数组分配值。您不能添加到数组,这是一个列表。。如果您在
foreach
循环中执行此操作,则集合将在迭代时被修改。抱歉,但这仍然是错误的答案,也是一个糟糕的答案:使用
foreach
是为了访问数组的元素,您无法以这种方式填充它们啊,我在原始问题中完全忽略了foreach循环。第一个问题给了我更多的错误,到目前为止,我对c#的了解只有两周了,呵呵。第二个很有魅力。谢谢你
int Min = 0;
int Max = 20;
Random randNum = new Random();
int[] test2 = Enumerable
    .Repeat(0, 5)
    .Select(i => randNum.Next(Min, Max))
    .ToArray();