一个 C++ 程序来检查对合矩阵
假设给定一个矩阵 M[r][c],'r' 表示行数,'c' 表示列数,满足 r = c,形成一个方阵。我们需要检查给定的方阵是否为对合矩阵。
对合矩阵
当矩阵与自身相乘,结果是一个单位矩阵时,该矩阵被称为对合矩阵。单位矩阵 I 是一个沿主对角线元素均为 1,而其他元素均为 0 的矩阵。因此,我们可以说一个矩阵是对合矩阵当且仅当M*M=I,其中M 是某个矩阵,I 是单位矩阵。
如以下示例所示 −
当我们把矩阵与自身相乘时,结果是单位矩阵;因此给定的矩阵是对合矩阵。
例
Input: { {1, 0, 0}, {0, -1, 0}, {0, 0, -1}} Output: yes Input: { {3, 0, 0}, {0, 2, 0}, {0, 0, 3} } Output: no
算法
Start Step 1 -> define macro as #define size 3 Step 2 -> declare function for matrix multiplication. void multiply(int arr[][size], int res[][size]) Loop For int i = 0 and i < size and i++ Loop For int j = 0 and j < size and j++ Set res[i][j] = 0 Loop For int k = 0 and k < size and k++ Set res[i][j] += arr[i][k] * arr[k][j] End End End Step 3 -> declare function to check involutory matrix or not bool check(int arr[size][size]) declare int res[size][size] Call multiply(arr, res) Loop For int i = 0 and i < size and i++ Loop For int j = 0 and j < size and j++ IF (i == j && res[i][j] != 1) return false End If (i != j && res[i][j] != 0) return false End End End Return true Step 4 -> In main() Declare int arr[size][size] = { { 1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } } If (check(arr)) Print its an involutory matrix Else Print its not an involutory matrix Stop
例
#include <bits/stdc++.h> #define size 3 using namespace std; // matrix multiplication. void multiply(int arr[][size], int res[][size]){ for (int i = 0; i < size; i++){ for (int j = 0; j < size; j++){ res[i][j] = 0; for (int k = 0; k < size; k++) res[i][j] += arr[i][k] * arr[k][j]; } } } // check involutory matrix or not. bool check(int arr[size][size]){ int res[size][size]; multiply(arr, res); for (int i = 0; i < size; i++){ for (int j = 0; j < size; j++){ if (i == j && res[i][j] != 1) return false; if (i != j && res[i][j] != 0) return false; } } return true; } int main(){ int arr[size][size] = { { 1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } }; if (check(arr)) cout << "its an involutory matrix"; else cout << "its not an involutory matrix"; return 0; }
输出
its an involutory matrix
广告