C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am having trouble figuring this out. I need to put items in a 3x3 rectangular array and then average them. This is my code for putting the values in the array:
// Add Values to Rectangular Array
for (int i = 0; i < retailPrices.GetLength(0); i++)
{
for (int j = 0; j < retailPrices.GetLength(1); j++)
{
retailPrices[i, 0] = wholesaleCost;
retailPrices[i, 1] = markupPercentage;
retailPrices[i, 2] = futureValue;
}
}
This is my code for my GetAverage Method:
private decimal GetAverage(decimal[,] retailPrices)
{
decimal sum = 0m;
for (int i = 0; i < retailPrices.GetLength(0); i++)
{
for (int j = 0; j < retailPrices.GetLength(1); j++)
{
sum += retailPrices[i, j];
}
}
decimal average = sum / retailPrices.GetLength(0);
return average;
}
What is the correct way to do this? What am I doing incorrectly? Please correct my code.
To calculate the average of all nine values:
using System.Linq;
. . .
private decimal GetAverage( decimal[,] retailPrices )
{
return retailPrices.Cast<decimal>( ).Average( );
}
You need to calc the size of the arrays.
private decimal GetAverage(decimal[,] retailPrices)
{
decimal sum = 0m;
decimal count =0m;
for (int i = 0; i < retailPrices.Length; i++)
{
count += retailPrices[i].Length;
for (int j = 0; j < retailPrices[i].Length; j++)
{
sum += retailPrices[i, j];
}
}
decimal average = sum / count;
return average;
}