Reputation: 13
This is my code:
I am trying to get the maximum per line, everything is going ok until the last row. It shows me 8, but should be 4.
int[,] vek = new int[,] { { 2, 5 }, { 4, 5 }, { 8, 5 }, { 4, 2 } };
int sumL=0;
double media = 0;
int maxL = 0;
maxL = vek [0,0];
Console.WriteLine("\tL1\tL2\tTotal\tMedia");
Console.WriteLine();
for (int row = 0; row < vek.GetLength(0); row++)
{
Console.Write("{0}.\t", row + 1);
for (int col = 0; col < vek.GetLength(1); col++) {
Console.Write(vek[row, col] + "\t");
sumL += vek[row, col];// SUMA
media = (double)sumL / vek.GetLength(1); //Media
if (maxL < vek[row,col])
{
maxL = vek[row, col];
}
}
Console.WriteLine(sumL + "\t" + media + "\t" + maxL);
Console.WriteLine();
}
Console.ReadKey();
}
Upvotes: 0
Views: 57
Reputation: 482
You need to set maxL
back to 0 (or, better yet, int.MinValue
) at the start of each row. Simply moving its declaration into the outer for loop would be a good way to do this.
Your code gets 5, 5, 8, 8 for the maximum because, without reseting maxL
, it's taking the maximum of the rows so far instead of the maximum of each row independently.
Upvotes: 2