Определить, является ли произведение матриц перестановочным - C#
Формулировка задачи:
Заданы две матрицы А(3, 3) и В(3, 3). Написать программу проверки - является ли произведение этих матриц перестановочным, т.е. проверить равенство AB = ВА. Помогите пожалуйста.
Решение задачи: «Определить, является ли произведение матриц перестановочным»
textual
Листинг программы
- using System;
- namespace ConsoleApplication3
- {
- class Program
- {
- static double[,] MatrixMultiplication(double[,] firstMatrix, double[,] secondMatrix)
- {
- if (firstMatrix.GetLength(1) != secondMatrix.GetLength(0))
- throw new Exception();
- double[,] result = new double[firstMatrix.GetLength(0), secondMatrix.GetLength(1)];
- for (int i = 0; i < firstMatrix.GetLength(0); i++)
- for (int j = 0; j < secondMatrix.GetLength(1); j++)
- for (int k = 0; k < secondMatrix.GetLength(0); k++)
- result[i, j] += firstMatrix[i, k] * secondMatrix[k, j];
- return result;
- }
- static bool CheckEqual(double[,] firstMatrix, double[,] secondMatrix)
- {
- for (int i = 0; i < firstMatrix.GetLength(0); i++)
- for (int j = 0; j < secondMatrix.GetLength(1); j++)
- if (firstMatrix[i, j] != secondMatrix[i, j])
- return false;
- return true;
- }
- static void Main(string[] args)
- {
- double[,] firstMatrix = new double[3, 3] { { 1, 1, 1 }, { 2, 2, 2 }, { 1, 1, 1 } };
- double[,] secondMatrix = new double[3, 3] { { 1, 1, 1 }, { 2, 2, 2 }, { 1, 1, 1 } };
- try
- {
- if (CheckEqual(MatrixMultiplication(firstMatrix, secondMatrix), MatrixMultiplication(secondMatrix, firstMatrix)))
- Console.WriteLine("AB = BA");
- else
- Console.WriteLine("AB != BA");
- }
- catch(Exception)
- {
- Console.WriteLine("Матрицы не могут быть умноженными.");
- }
- Console.ReadKey();
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д