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

更新日期: 2019-09-23

1K+ 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.