Где ошибка при вводе 2 массива? - C#
Формулировка задачи:
Пожалуйста помогите разобраться почему при выводе 2 массива возникает ошибка?
using System.IO;
using System;
/*
Алгоритмы работы с многомерными массивами
(матрицы, кубы и т.д., срезы многомерных массивов, сложение,
разность, умножение матриц, нахождение обратной матрицы,
определителя для матриц произвольной размерности)
*/
class Program
{
// Динамическое сложение
private static T Add<T>(T t1, T t2)
{
dynamic a = t1;
dynamic b = t2;
return a + b;
}
// Динамическая разность
private static T Sub<T>(T t1, T t2)
{
dynamic a = t1;
dynamic b = t2;
return a - b;
}
// Динамическое умножение
private static T Mult<T>(T t1, T t2)
{
dynamic a = t1;
dynamic b = t2;
return a * b;
}
// Динамическое деление
private static T Division<T>(T t1, T t2)
{
dynamic a = t1;
dynamic b = t2;
return a / b;
}
// Конвертация массива в простейший JSON
public static string ArrToBasicJSON<T>(T[] arr)
{
string str = "";
str += "[";
for (int x = 0, lenX = arr.GetLength(0); x < lenX; x++)
{
if (x > 0) { str += ", "; };
str += arr[x].ToString();
}
str += "]";
return str;
}
public static string Arr2DToBasicJSON<T>(T[,] arr)
{
string str = "";
for (int x = 0, lenX = arr.GetLength(0); x < lenX; x++)
{
if (x > 0) { str += ", \n"; };
str += "[";
for (int y = 0, lenY = arr.GetLength(1); y < lenY; y++)
{
if (y > 0) { str += ", "; };
str += arr[x, y].ToString();
}
str += "]";
}
return str;
}
public static string Arr22DToBasicJSON<T>(T[,] arr)
{
string str = "";
for (int xx = 0, lenX = arr.GetLength(0); xx < lenX; xx++)
{
if (xx > 0) { str += ", \n"; };
str += "[";
for (int yy = 0, lenY = arr.GetLength(1); yy < lenY; yy++)
{
if (yy > 0) { str += ", "; };
str += arr[xx, yy].ToString();
}
str += "]";
}
return str;
}
// Срез массива
public static T[] Slice<T>(T[] source, int start, int end)
{
int count;
count = end - start;
T[] target = null;
if (count > 0)
{
target = new T[count];
for (int i = start; i < end; i++)
{
target[i - start] = source[i];
}
}
return target;
}
// Срез двумерного массива
public static T[,] Slice2D<T>(T[,] source, int startY, int endY, int startX, int endX)
{
int countX;
int countY;
countX = endX - startX;
countY = endY - startY;
T[,] target = new T[countX, countY];
for (int x = 0; x < countX; x++)
{
for (int y = 0; y < countY; y++)
{
target[x, y] = source[x + startY, y + startX];
}
}
return target;
}
// Сумма матриц
public static T[,] Add2D<T>(T[,] arr_1, T[,] arr_2)
{
int lenX_1, lenX_2, lenX_max;
int lenY_1, lenY_2, lenY_max;
lenX_1 = arr_1.GetLength(0);
lenY_1 = arr_1.GetLength(1);
lenX_2 = arr_2.GetLength(0);
lenY_2 = arr_2.GetLength(1);
lenX_max = Math.Max(lenX_1, lenX_2);
lenY_max = Math.Max(lenY_1, lenY_2);
T[,] target = new T[lenX_max, lenY_max];
for (int x = 0; x < lenX_max; x++)
{
for (int y = 0; y < lenY_max; y++)
{
if (x < lenX_1 && y < lenY_1)
{
T item_1 = arr_1[x, y];
// Замена нулей
target[x, y] = Add<T>(target[x, y], item_1);
}
if (x < lenX_2 && y < lenY_2)
{
T item_2 = arr_2[x, y];
target[x, y] = Add<T>(target[x, y], item_2);
}
}
}
return target;
}
// Разность матриц
public static T[,] Sub2D<T>(T[,] arr_1, T[,] arr_2)
{
int lenX_1, lenX_2, lenX_max;
int lenY_1, lenY_2, lenY_max;
lenX_1 = arr_1.GetLength(0);
lenY_1 = arr_1.GetLength(1);
lenX_2 = arr_2.GetLength(0);
lenY_2 = arr_2.GetLength(1);
lenX_max = Math.Max(lenX_1, lenX_2);
lenY_max = Math.Max(lenY_1, lenY_2);
T[,] target = new T[lenX_max, lenY_max];
for (int x = 0; x < lenX_max; x++)
{
for (int y = 0; y < lenY_max; y++)
{
if (x < lenX_1 && y < lenY_1)
{
T item_1 = arr_1[x, y];
// Замена нулей
target[x, y] = Add<T>(target[x, y], item_1);
}
if (x < lenX_2 && y < lenY_2)
{
T item_2 = arr_2[x, y];
target[x, y] = Sub<T>(target[x, y], item_2);
}
}
}
return target;
}
// Умножение матриц
public static T[,] Mult2D<T>(T[,] arr_1, T[,] arr_2)
{
int lenX_1, lenX_2;
int lenY_1, lenY_2;
lenX_1 = arr_1.GetLength(0);
lenY_1 = arr_1.GetLength(1);
lenX_2 = arr_2.GetLength(0);
lenY_2 = arr_2.GetLength(1);
// Проверка на допустимость операции
if (lenY_1 != lenX_2)
{
throw new System.InvalidOperationException("Нельза умножать несогласованные матрицы.");
}
T[,] target = new T[lenX_1, lenY_2];
for (int k = 0; k < lenY_2; k++)
{
for (int i = 0; i < lenX_1; i++)
{
for (int j = 0; j < lenX_2; j++)
{
T item_1 = arr_1[i, j];
T item_2 = arr_2[j, k];
target[i, k] = Add<T>(target[i, k], Mult<T>(item_1, item_2));
}
}
}
return target;
}
// Транспонирование матрицы
public static T[,] Trans<T>(T[,] arr)
{
int lenX = arr.GetLength(0);
int lenY = arr.GetLength(1);
T[,] target = new T[lenY, lenX];
for (int i = 0; i < lenX; i++)
{
for (int j = 0; j < lenY; j++)
{
target[j, i] = arr[i, j];
}
}
return target;
}
// Определитель матрицы 2 x 2
public static int Determinant2(int[,] x1)
{
int md2 = x1[0, 0] * x1[1, 1]
- x1[1, 0] * x1[0, 1];
return md2;
}
// Определитель матрицы 3 x 3
public static int Determinant3(int[,] x1)
{
int md3 = x1[0, 0] * x1[1, 1] * x1[2, 2]
+ x1[2, 0] * x1[0, 1] * x1[1, 2]
+ x1[1, 0] * x1[2, 1] * x1[0, 2]
- x1[2, 0] * x1[1, 1] * x1[0, 2]
- x1[0, 0] * x1[2, 1] * x1[1, 2]
- x1[1, 0] * x1[0, 1] * x1[2, 2];
return md3;
}
public static bool Str_to_bool(string str)
{
bool ans = false;
switch (str)
{
case "y":
case "Y":
case "yes":
case "Yes":
case "д":
case "Д":
case "да":
case "Да":
ans = true;
break;
default:
ans = false;
break;
}
return ans;
}
static void Main()
{
Console.WriteLine("Введите размерность массива: ");
Console.WriteLine("x: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("y: ");
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("нужен ли второй массив? y/n: ");
bool has_seccond_arr = Str_to_bool(Console.ReadLine());
Console.WriteLine("Введите размерность 2 массива: ");
Console.WriteLine("x: ");
int xx = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("y: ");
int yy = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("желаете воодить сами (n) или ввести случайные значения (y)? y/n: ");
bool is_auto_fill = Str_to_bool(Console.ReadLine());
// 1
int[,] array2D_1 = new int[x, y];
// 2
int[,] array2D_2 = new int[x, y];
if (is_auto_fill)
{
Random random = new Random();
for (int c_x = 0; c_x < x; c_x++)
{
for (int c_y = 0; c_y < y /* !!! */; c_y++)
{
array2D_1[c_x, c_y] = random.Next(-42, 42);
if (has_seccond_arr)
{
for (int c_xx = 0; c_xx < xx; c_xx++)
{
for (int c_yy = 0; c_yy < yy /* !!! */; c_yy++)
{
array2D_2[c_xx, c_yy] = random.Next(-42, 42);
}
}
}
}
}
}
else
{
Console.WriteLine(has_seccond_arr ? "Первый массив" : "Введите элементы массива");
for (int c_x = 0; c_x < x; c_x++)
{
for (int c_y = 0; c_y < y /* !!! */; c_y++)
{
array2D_1[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
}
}
if (has_seccond_arr)
{
Console.WriteLine("Второй массив");
for (int c_x = 0; c_x < x; c_x++)
{
for (int c_y = 0; c_y < y /* !!! */; c_y++)
{
array2D_2[c_x, c_y] = Convert.ToInt32(Console.ReadLine());
}
}
}
}
Console.WriteLine("\n\n");
Console.WriteLine(has_seccond_arr ? "Первый массив" : "Массив");
Console.WriteLine(Arr2DToBasicJSON(array2D_1));
if (has_seccond_arr)
{
Console.WriteLine("Второй массив");
Console.WriteLine(Arr22DToBasicJSON(array2D_2));
}
Console.WriteLine("\n\n");
Console.WriteLine("Выберите операцию:");
Console.WriteLine(
" 1) Срез двумерного массива \n"
+ " 2) Сложение матриц \n"
+ " 3) Разность матриц \n"
+ " 4) Умножение матриц \n"
+ " 5) Транспонирование матрицы \n"
+ " 6) Определитель матрицы 2 x 2 \n"
+ " 7) Определитель матрицы 3 x 3 \n"
);
int variant = Convert.ToInt32(Console.ReadLine());
switch (variant)
{
// Срез двумерного массива
case 1:
Console.WriteLine("Введите начала среза по Y:");
int slice_y_start = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите конец среза по Y:");
int slice_y_end = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите начала среза по X:");
int slice_x_start = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите конец среза по X:");
int slice_x_end = Convert.ToInt32(Console.ReadLine());
array2D_1 = Slice2D(
array2D_1
, slice_y_start
, slice_y_end
, slice_x_start
, slice_x_end
);
Console.WriteLine(Arr2DToBasicJSON(array2D_1));
break;
// Сложение матриц
case 2:
Console.WriteLine(Arr2DToBasicJSON(Add2D(array2D_1, array2D_2)));
break;
// Разность матриц
case 3:
Console.WriteLine(Arr2DToBasicJSON(Sub2D(array2D_1, array2D_2)));
break;
// Умножение матриц
case 4:
Console.WriteLine(Arr2DToBasicJSON(Mult2D(array2D_1, array2D_2)));
break;
// Транспонирование матрицы
case 5:
Console.WriteLine(Arr2DToBasicJSON(Trans(array2D_1)));
break;
// Определитель матрицы 2 x 2
case 6:
Console.WriteLine(Determinant2(array2D_1));
break;
// Определитель матрицы 3 x 3
case 7:
default:
Console.WriteLine(Determinant3(array2D_1));
break;
}
Console.ReadLine();
}
}Решение задачи: «Где ошибка при вводе 2 массива?»
textual
Листинг программы
// 1 int[,] array2D_1 = new int[x, y]; // 2 int[,] array2D_2 = new int[x, y]; //вот здесь