C 语言程序检查矩阵是否为单位矩阵


2023 年 1 月 9 日, Learn eTutorial
2420

什么是单位矩阵?

单位矩阵(或称单位方阵)是一个方阵,其主对角线上元素为 1,其余所有元素均为 0。在此 C 语言程序中,我们需要检查给定的输入是否为单位矩阵。

如何使用 C 语言程序检查单位矩阵?

此 C 语言程序的逻辑是,首先声明矩阵。然后将矩阵的阶数读取到 RC 变量中。接着使用 `for` 循环读取矩阵的元素。然后显示矩阵。现在检查数组的每个元素是否不等于 1 且不等于 0,如果为真,则设置 Flag=0 并退出循环。如果 flag=1 则显示其为单位矩阵,否则,显示其不是单位矩阵。

算法

步骤 1: 包含头文件以使用 C 语言程序中的内置函数。

步骤 2: 声明整数数据类型的矩阵 mat

步骤 3: 声明变量 i, j, R, C, flag

步骤 4: 设置 flag=1

步骤 5: 将矩阵的阶数读取到变量 RC 中。

步骤 6: 使用嵌套的 `for` 循环,条件为 i < R, j < C,读取 mat[i][j] 的元素。

步骤 7: 使用 `for` 循环显示输入矩阵 mat 的元素。

步骤 8: 使用嵌套的 `for` 循环,条件为 i < R, j < C,检查如果 mat[i][j] != 1 && mat[j][i] !=0,则设置 flag=0 并从循环中 `break`。否则,重复循环进行下一次迭代。

步骤 9: 现在检查如果 flag==1 则显示其为单位矩阵,否则显示其不是单位矩阵。


为了在 C 语言中检查单位矩阵,我们使用了以下概念。我们建议您学习这些概念以获得更好的理解。

C 语言源代码

                                          #include <stdio.h>

void main() 
{
   int mat[10][10];
   int i, j, R, C, flag = 1;
   printf("Enter the order of the matrix\n"); /* enter the order of the matrix */
   scanf("%d %d", & R, & C);
   printf("\nEnter the elements of matrix\n");
   for (i = 0; i < R; i++) 
   {
      for (j = 0; j < C; j++) 
      {
          scanf("%d", & mat[i][j]);
      }
   }
   printf("\nMATRIX is\n"); /* printing the matrix input by the user */
   for (i = 0; i < R; i++) 
   {
       for (j = 0; j < C; j++) 
       {
            printf("%d ", mat[i][j]);
       }
       printf("\n\n");
    }
  for (i = 0; i < R; i++) /* Check for unit (or identity) matrix */ {
    for (j = 0; j < C; j++) {
        if (mat[i][j] != 1 && mat[j][i] != 0) {
            flag = 0;
            break;
        }
    }
  }
  if (flag == 1)
    printf("It is an identity matrix\n");
  else
    printf("It is not an identity matrix\n");
}
                                      

输出

Run 1

Enter the order of the matrix
2 2

Enter the elements of matrix
2 2
1 2

MATRIX is
2  2
1  2

It is not an identity matrix
Run 2

Enter the order of the matrix
2 2

Enter the elements of matrix
1 0
0 1

MATRIX is
1  0
0  1
It is an identity matrix