Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c# - Making an array of random ints

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);
}

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...