如何在C#中填充2D数组? [英] how to populate a 2D array in C#?
本文介绍了如何在C#中填充2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用随机值填充c#中的二维数组..我已经坚持了......这是我的代码
i'm trying to populate a 2d array in c# using random values .. i've stucked...here is my code
Random random = new Random();
int[ , ] numbers = new int[ no_of_rows , no_of_columns ];
int row_value = 0;
int column_value = 0;
// populating 2D Array
for (int m = 0; m < 5 ; m++)
{
for (int n = 0; n < 5 ; n++)
{
row_value = random.Next(0,25);
column_value = random.Next(0, 25);
numbers[m,n] = [row_value,column_value];
}
}
推荐答案
// random integer returned can include this value
private const int randMinimum = 0;
// note that random integer returned maximum value will be
// one less than the value specified: i.e., in this case, #25
private const int randMaximum = 26;
private const int no_of_rows = 5;
private const int no_of_columns = 5;
// fancy way of getting more randomness than you will probably ever need
private Random random = new Random(Guid.NewGuid().GetHashCode());
private int[ , ] numbers = new int[ no_of_rows , no_of_columns ];
// populating 2D Array
for (int row = 0; row < no_of_rows; row++)
{
for (int column = 0; column < no_of_columns; column++)
{
numbers[row, column] = random.Next(randMinimum, randMaximum);
}
}
试试以下代码
Try the below code
Random random = new Random();
int[ , ] numbers = new int[5,5];
//populating 2D Array
for (int m = 0; m < 5 ; m++)
{
for (int n = 0; n < 5 ; n++)
{
numbers[m,n] = random.Next(0, 25);
}
}
希望有所帮助
Hope it helps
这篇关于如何在C#中填充2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文