Найдите произведение двух матриц - C#
Формулировка задачи:
Всем привет, сделал задание:
Найдите произведение двух матриц 2х2.
но без использования структуры.
К теме прикрепил саму задачу. Заранее благодарю)
Решение задачи: «Найдите произведение двух матриц»
textual
Листинг программы
struct Matrix22
{
private int a11, a12, a21, a22; //элементы матрицы
public Matrix22(int a11, int a12, int a21, int a22)
{
this.a11 = a11;
this.a12 = a12;
this.a21 = a21;
this.a22 = a22;
}
public int this[int i, int j] //Индексатор
{
get
{
if (i == 0)
{
if (j == 0)
return a11;
if (j == 1)
return a12;
}
if (i == 1)
{
if (j == 0)
return a21;
if (j == 1)
return a22;
}
throw new IndexOutOfRangeException();
}
set
{
if ((i != 0 && i != 1) || (j != 0 && j != 1))
throw new IndexOutOfRangeException();
if (i == 0)
{
if (j == 0)
a11 = value;
else
a12 = value;
}
else
{
if (j == 0)
a21 = value;
else
a22 = value;
}
}
}
public static Matrix22 operator *(Matrix22 a, Matrix22 b) //переопределение оператора *
{
Matrix22 res = new Matrix22();
res[0, 0] = a[0, 0] * b[0, 0] + a[0, 1] * b[1, 0];
res[0, 1] = a[0, 0] * b[0, 1] + a[0, 1] * b[1, 1];
res[1, 0] = a[1, 0] * b[0, 0] + a[1, 1] * b[1, 0];
res[1, 1] = a[1, 0] * b[0, 1] + a[1, 1] * b[1, 1];
return res;
}
public override string ToString()
{
return string.Format("{0} {1}\n{2} {3}", a11, a12, a21, a22);
}
}
static void Main(string[] args)
{
Matrix22 m1 = new Matrix22(1,2,3,4);
Matrix22 m2 = new Matrix22(5,6,7,8);
Console.WriteLine(m1);
Console.WriteLine();
Console.WriteLine(m2);
Console.WriteLine();
Console.WriteLine(m1 * m2);
Console.ReadKey();
}