介绍
在本实验中,我们将学习如何使用 C 编程语言检查一个方阵是否对称。如果一个方阵等于它的转置矩阵,则该方阵被称为对称矩阵。我们将找到矩阵的转置矩阵,并将其与原始矩阵进行比较,以检查其对称性。
注意:你需要自己创建文件
~/project/main.c来练习编码,并学习如何使用 gcc 编译和运行它。
cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main
声明变量并输入矩阵
首先,我们需要声明变量并从用户那里输入矩阵。我们将使用嵌套循环来输入矩阵。为了从用户那里输入矩阵,我们首先询问用户矩阵的维度并将其存储在 n 中。然后,我们使用循环输入矩阵的每个元素。
#include <stdio.h>
int main() {
int c, d, a[10][10], b[10][10], n;
printf("\nEnter the dimension of the matrix: \n\n");
scanf("%d", &n);
printf("\nEnter the %d elements of the matrix: \n\n", n * n);
for (c = 0; c < n; c++)
for (d = 0; d < n; d++)
scanf("%d", &a[c][d]);
return 0;
}
求矩阵的转置
矩阵的转置是通过交换行和列的索引来实现的。我们使用嵌套循环来求出矩阵的转置。为了找到矩阵的转置,我们使用两个循环。第一个循环遍历行,第二个循环遍历列。
// finding transpose of a matrix and storing it in b[][]
for (c = 0; c < n; c++)
for (d = 0; d < n; d++)
b[d][c] = a[c][d];
检查矩阵的对称性
在这一步中,我们将检查原始矩阵是否与其转置矩阵相同。我们使用嵌套循环来实现这一检查。为了检查矩阵的对称性,我们使用两个循环。第一个循环遍历行,第二个循环遍历列。
// checking if the original matrix is the same as its transpose
for (c = 0; c < n; c++)
for (d = 0; d < n; d++)
if (a[c][d] != b[c][d]) {
printf("\n\nMatrix is not Symmetric\n\n");
exit(0); // a system defined method to terminate the program
}
打印结果
在确认矩阵是对称的之后,程序会显示一条消息以确认这一点。如果矩阵不对称,程序将终止。
// If the program is not terminated yet, it means the matrix is symmetric
printf("\n\nMatrix is Symmetric\n\n");
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
总结
在本实验中,我们学习了如何使用 C 编程语言检查一个方阵是否对称。我们使用嵌套循环来输入矩阵并找到其转置矩阵,然后检查原始矩阵是否与其转置矩阵相同。如果两个矩阵相同,程序会显示一条消息,表明矩阵是对称的。



