简体   繁体   中英

How to calculate the average of each row in multidimensional array

What i want to do is get the average of each row of what the user inputs. I'm able to display the input, but not sure how to calculate an average of the three numbers in each row. What would be a solution? I'm new to C# so still learning.

Here's my code:

class Program
    {
        static void Main(string[] args)
        {
            int[,] number = new int[3, 5];
            for (int i = 0; i < 3; i++)
            {
                for (int x = 0; x < 3; x++)
                {
                    Console.WriteLine("Please enter number");
                    number[x, i] = int.Parse(Console.ReadLine());
                }
            }

            for (int i = 0; i < 3; i++)
            {
                for (int x = 0; x < 3; x++)
                {
                    Console.Write(number[x, i] + " ");
                }
                Console.WriteLine(" ");
                Console.ReadLine();
            }
        }
    } 

You can do it something like this

for(int i = 0; i < 3; i++)
{
    int Avg = 0;
    for(int x = 0; x < 3; x++)
    {
        Console.Write(number[x, i] + " ");
        Avg += number[x, i];
    }
    Avg = Avg / 3;
    Console.Write("Average is" + Avg);
    Console.WriteLine(" ");
    Console.ReadLine();
}

I think you have to create a method like the following, that will accept a two dimensional array as input and iterate through its rows and further iteration will performed through its cols to find the sum of all elements in each rows and then it will be divided with number of cols, to get the average. Take a look into the method

public static void rowWiseAvg(int[,] inputArray)
{
    int rows = inputArray.GetLength(0);
    int cols = inputArray.GetLength(1);

    for (int i = 0; i < rows; i++)
    {
        float rowAvg = 0;
        for (int x = 0; x < cols; x++)
        {                  
            rowAvg += inputArray[i,x];
        }
        rowAvg = rowAvg / cols;
        Console.Write("Average of row {0} is :{1}", i,rowAvg);         
    }
}

An additional note for you : When you are reading values for a multi-dimensional array, use outer loop to read values for the rows and inner loop for reading columns. in your case you are actually reads the columns first then gets values for each rows in a column. One more, use float / double to store the average

Here's a (mostly) LINQ solution:

var array = new int[,] 
{ 
    { 1, 2, 3, 4 }, 
    { 5, 6, 7, 8 }, 
    { 9, 10, 11, 12 } 
};

int count = 0;
var averages = array.Cast<int>()
                    .GroupBy(x => count++ / array.GetLength(1))
                    .Select(g => g.Average())
                    .ToArray();

// [2.5, 6.5, 10.5]

The simplest way is to use for loops, as described in other answers.
You can also utilize LINQ and use Enumerable.Range to make it another way:

public static class MultidimensionalIntArrayExtensions
{
    // Approach 1 (using Select and Average)
    public static double[] RowAverages(this int[,] arr)
    {
        int rows = arr.GetLength(0);
        int cols = arr.GetLength(1);

        return Enumerable.Range(0, rows)
            .Select(row => Enumerable
                .Range(0, cols)
                .Select(col => arr[row, col])
                .Average())
            .ToArray();
    }

    // Approach 2 (using Aggregate)
    public static double[] RowAverages(this int[,] arr)
    {
        int rows = arr.GetLength(0);
        int cols = arr.GetLength(1);

        return Enumerable.Range(0, rows)
            .Select(row => Enumerable
                .Range(0, cols)
                .Aggregate(0.0, (avg, col) => avg + ((double)arr[row, col] / cols)))
            .ToArray();
    }
}

// Usage:
int[,] arr =
{
    { 1, 2, 3 },
    { 2, 3, 4 },
    { 3, 4, 5 },
    { 6, 7, 8 },
    { 1, 1, 1 }
};

double[] rowSums = arr.RowAverages(); // [2, 3, 4, 7, 1]

This code may look unreadable and non-OOP for some developers; and may seem good and laconic for others. If your belongs to the second group, use this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM