C 中单位矩阵程序
给定一个方矩阵 M[r][c] 其中 'r' 是某些行数,'c' 是列数,使得 r = c,我们必须检查 'M' 是否为单位矩阵。
单位矩阵
单位矩阵也被称为 n×n 方矩阵的单位矩阵,其中对角线元素仅具有整数值 1,非对角线元素仅具有整数值 0
就像在下面给出的示例中 −
$$I1=\begin{bmatrix}1 \end{bmatrix},\ I2=\begin{bmatrix}1 & 0 \0 & 1 \end{bmatrix},\ I3=\begin{bmatrix}1 &0 & 0 \0 &1 & 0 \0 &0 &1 \end{bmatrix},\In=\begin{bmatrix}
1 &0 &0 &...&0 \
0 &1 &0 &...&0\
0 &0 &1 &...&0\
. &. &. &...&.\
. &. &. &...&.\
0 &0 &0 &...&1\
\end{bmatrix} $$
示例
Input: m[3][3] = { {1, 0, 0}, {0, 1, 0}, {0, 0, 1}} Output: yes Input: m[3][3] == { {3, 0, 1}, {6, 2, 0}, {7, 5, 3} } Output: no
算法
Start Step 1 -> declare function for finding identity matrix int identity(int num) declare int row, col Loop For row = 0 and row < num and row++ Loop For col = 0 and col < num and col++ IF (row = col) Print 1 Else Print 0 End End Step 2 -> In main() Declare int size = 4 Call identity(size) Stop
示例
#include<stdio.h> int identity(int num){ int row, col; for (row = 0; row < num; row++){ for (col = 0; col < num; col++){ if (row == col) printf("%d ", 1); else printf("%d ", 0); } printf("
"); } return 0; } int main(){ int size = 4; identity(size); return 0; }
输出
1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
广告