簡體   English   中英

在C#中查找2D數組中值的總和

[英]Finding the sum of the values in a 2D Array in C#

嘗試構建一種方法,該方法將查找2D數組內所有值的總和。 我對編程非常陌生,無法找到一個很好的起點來嘗試弄清楚它是如何完成的。 到目前為止,這就是我所擁有的(原諒我,我通常是英國/歷史上的人,邏輯不是我的專長...)

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循環將它們加起來? 將它們加起來並返回整數? 如果有人能提出任何見解,將不勝感激,謝謝!

首先,您不需要在每個方法的開頭都調用FillArray,您已經在main方法中填充了數組,將填充的數組傳遞給了其他方法。

最類似於您用來填充數組的循環是最容易理解的:

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

如果知道長度很簡單,就可以對數組求和。附帶的獎金代碼也能獲得最高的價值。 您可以輕松地對此進行擴展以獲取其他類型的統計代碼。 我假設Xlength和Ylength以下也是整數,並且為您所知。 您也可以在代碼中用數字替換它們。

int total = 0;
int max=0;
int t=0;  // temp valeu
For (int x=0;x<Xlength;x++)
{
 for (int y=0;y<Ylength;y++)
 {
   t = yourArray[x,y]; 
   total =total +t;
   if(t>max){max=t;}   // an if on a single line
 }
}

這是有關如何檢索未知數組長度的MSDN示例的鏈接。 當您開始使用c#google“ .net perls”時,周圍有一個不錯的網站

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM