如何编写 C 语言程序来检查矩阵是否为单位矩阵,并附带示例。单位矩阵是一个方阵,其主对角线元素为 1,所有其他元素为 0。

C 语言检查矩阵是否为单位矩阵的程序示例
此程序允许用户输入矩阵的行数和列数。接下来,我们将使用 For 循环检查给定的矩阵是否为单位矩阵。
#include<stdio.h>
int main()
{
int i, j, rows, columns, a[10][10], Flag = 1;
printf("\n Please Enter Number of rows and columns : ");
scanf("%d %d", &i, &j);
printf("\n Please Enter the Matrix Elements \n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
scanf("%d", &a[rows][columns]);
}
}
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
if(a[rows][columns] != 1 && a[columns][rows] != 0)
{
Flag = 0;
break;
}
}
}
if(Flag == 1)
{
printf("\n The Matrix that you entered is an Identity Matrix ");
}
else
{
printf("\n The Matrix that you entered is Not an Identity Matrix ");
}
return 0;
}

在此“检查矩阵是否为单位矩阵的程序”中,我们声明了一个大小为 10*10 的二维数组。C 语言中的乘法。
下面的 C 编程语句提示用户输入矩阵大小(行数和列数。例如 2 行,2 列 = a[2][2])。
printf("\n Please Enter Number of rows and columns : ");
scanf("%d %d", &i, &j);
接下来,我们使用 for 循环遍历 a[2][2] 矩阵中的每个元素。for 循环中的条件((rows < i) 和 (columns < j))将确保编译器不会超出矩阵限制。否则,矩阵将溢出。for 循环内的 scanf 语句将用户输入的值存储在每个单独的数组元素中,例如 a[0][0]、a[0][1]、……。
for(rows = 0; rows < i; rows++).
{
for(columns = 0; columns < j; columns++)
{
scanf("%d", &a[rows][columns]);
}
}
在下一行,我们还有一个 for 循环来检查矩阵是否为单位矩阵。
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
if(a[rows][columns] != 1 && a[columns][rows] != 0)
{
Flag = 0;
break;
}
}
}
让我用其他值来尝试此程序。
Please Enter Number of rows and columns : 3 3
Please Enter the Matrix Elements
1 0 0
0 1 0
0 1 1
The Matrix that you entered is Not an Identity Matrix
C 语言检查矩阵是否为单位矩阵的程序示例 2
此程序与上面的示例类似。但是,这一次,我们使用 Else If 语句而不是 If 语句。
#include<stdio.h>
int main()
{
int i, j, rows, columns, a[10][10], Flag = 1;
printf("\n Please Enter Number of rows and columns : ");
scanf("%d %d", &i, &j);
printf("\n Please Enter the Matrix Elements \n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)
{
scanf("%d", &a[rows][columns]);
}
}
for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
if(rows == columns && a[rows][columns] != 1)
{
Flag = 0;
}
else if(rows != columns && a[rows][columns] != 0)
{
Flag = 0;
}
}
}
if(Flag == 1)
{
printf("\n The Matrix that you entered is an Identity Matrix ");
}
else
{
printf("\n The Matrix that you entered is Not an Identity Matrix ");
}
return 0;
}
单位矩阵输出
Please Enter Number of rows and columns : 3 3
Please Enter the Matrix Elements
1 0 0
0 1 0
0 0 1
The Matrix that you entered is an Identity Matrix