"Index was outside the bounds of the array" как можно исправить?
Выдает такую ошибку. суть задания в заданной квадратной матрице матрица вставляет 0 в элементы слева от главной диагонали и 1 в элементы справа от диагонали.
Console.WriteLine("Enter the number of rows");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the number of columns");
int m = int.Parse(Console.ReadLine());
int[,] matrix = new int[n, m];
Console.WriteLine($"Enter {n * m} items");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i, j] = int.Parse(Console.ReadLine());
}
}
for (int i = 1; i < matrix.Length; i++)
{
for (int j = 1; j < matrix.Length; j++)
{
if (j < i)
{
matrix[i, j] = 0;
}
if (j > i)
{
matrix[i, j] = 1;
}
Console.Write($"{matrix[i, j]} ");
}
Console.WriteLine();
}
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
matrix.Length - это общее число элементов, то есть n * m. И все-таки с нуля здесь надо перебирать элементы, а не с 1.
Надо так.
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
// ...
}
}