在C#中查找2D数组中值的总和 [英] Finding the sum of the values in a 2D Array in C#

查看:93
本文介绍了在C#中查找2D数组中值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试构建一种方法,该方法将查找2D数组内所有值的总和.我对编程非常陌生,无法找到一个很好的起点来尝试弄清楚它是如何完成的.到目前为止,这就是我所拥有的(原谅我,我通常是英国/历史上的人,逻辑不是我的专长...)

Trying to build a method that will find the sum of all the values within the 2D array. I'm very new to programming and can't find a good starting point on trying to figure out how its done. Here is what I have so far (forgive me, I'm usually an english/history guy, logic isn't my forte...)

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循环将它们加起来?将它们加起来并返回一个整数?如果有人能发表您的见解,将不胜感激,谢谢!

I guess I could try to find the sum of each row or column and add them up with a for loop? Add them up and return an int? If anyone could shed any insight, it would be greatly appreciated, thanks!

推荐答案

首先,您不需要在每个方法的开头都调用FillArray,您已经在main方法中填充了数组,您正在传递填充的排列到其他方法.

Firstly, you don't need to call FillArray in the beginning of each method, you have already populated the array in the main method, you are passing a populated array to these other methods.

类似于您用来填充数组的循环最容易理解:

A loop similar to what you use to populate the array is the easiest to understand:

//finds the sum of all values
public int SumArray(int[,] array)
{
    int total = 0;
    // Iterate through the first dimension of the array
    for (int i = 0; i < array.GetLength(0); i++)
    {
        // Iterate through the second dimension
        for (int j = 0; j < array.GetLength(1); j++)
        {
            // Add the value at this location to the total
            // (+= is shorthand for saying total = total + <something>)
            total += array[i, j];
        }
    }
    return total;
}

这篇关于在C#中查找2D数组中值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆