【发布时间】:2015-12-13 17:48:32
【问题描述】:
尝试构建一个方法来查找二维数组中所有值的总和。我对编程很陌生,找不到一个好的起点来试图弄清楚它是如何完成的。这是我到目前为止所拥有的(请原谅我,我通常是一个英语/历史专家,逻辑不是我的强项......)
class Program
{
static void Main(string[] args)
{
int[,] myArray = new int[5,6];
FillArray(myArray);
LargestValue(myArray);
}
//Fills the array with random values 1-15
public static void FillArray(int[,] array)
{
Random rnd = new Random();
int[,] tempArray = new int[,] { };
for (int i = 0; i < tempArray.GetLength(0); i++)
{
for (int j = 0; j < tempArray.GetLength(1); j++)
{
tempArray[i, j] = rnd.Next(1, 16);
}
}
}
//finds the largest value in the array (using an IEnumerator someone
//showed me, but I'm a little fuzzy on how it works...)
public static void LargestValue(int[,] array)
{
FillArray(array);
IEnumerable<int> allValues = array.Cast<int>();
int max = allValues.Max();
Console.WriteLine("Max value: " + max);
}
//finds the sum of all values
public int SumArray(int[,] array)
{
FillArray(array);
}
}
我想我可以尝试找到每一行或每一列的总和,然后用 for 循环将它们相加?将它们相加并返回一个 int?如果有人能提供任何见解,将不胜感激,谢谢!
【问题讨论】:
标签: c# multidimensional-array methods