C 语言程序,用于查找矩阵的迹和范数


2022年2月2日, Learn eTutorial
1471

为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题

在这个 C 语言程序中,我们需要计算矩阵的迹和范数。矩阵是相同数据类型元素的集合,我们以二维格式排列。矩阵也称为数组的数组。

如何计算矩阵的迹?

迹是矩阵主对角线所有元素的和。例如,矩阵 A 的迹是

2 5
2
1 是 3

如何计算矩阵的范数?

矩阵的范数是矩阵元素平方和的平方根。例如,矩阵 B 的范数

2 10
8  5
5。即 25 的平方根。

因此,在这个 C 语言程序中,我们所做的是初始化变量并导入头文件。然后使用嵌套的 for 循环接受一个矩阵并计算每个元素的平方。现在将乘积添加到 sum 变量。通过计算 sum 的平方根找出范数。

为了找到该矩阵的迹,我们启动一个 for 循环,在该循环中我们添加矩阵主对角线的元素。然后我们使用 printf 函数显示矩阵的范数和迹。

算法

第一步: 包含头文件,以便在C程序中使用内置函数。

步骤 2:包含头文件 math.h

步骤 3:声明变量 i, j, m, n, sum, sum1, a, normal 并设置 sum=0, sum1=0, a=0。

步骤 4:将矩阵的阶读入变量 m n

步骤 5:使用嵌套的 for 循环将矩阵的系数读入数组 ma[i][j] 并计算 a=ma[i][j]*ma[i][j] ,sum1=sum1+a

步骤 6:计算 Normal=sqrt(sum1)

步骤 7:显示给定矩阵的范数是 normal。

步骤 8:使用条件为 ifor 循环

步骤 9:将矩阵的迹显示为 sum

C 语言源代码

                                          #include <stdio.h>
#include <math.h>

void main() {
  static int ma[10][10];
  int i, j, m, n, sum = 0, sum1 = 0, a = 0, normal;
  printf("Enter the order of the matrix\n");
  scanf("%d %d", & m, & n);
  printf("Enter the no coefficients of the matrix \n");
  for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j) {
      scanf("%d", & ma[i][j]);
      a = ma[i][j] * ma[i][j];
      sum1 = sum1 + a;
    }
  }
  normal = sqrt(sum1);
  printf("The normal of the given matrix is = %d\n", normal);
  for (i = 0; i < m; ++i) {
    sum = sum + ma[i][i];
  }
  printf("Trace of the matrix is = %d\n", sum);
} /*End of main() */
                                      

输出

Enter the order of the matrix
3*3

Enter the n coefficients of the matrix
1 2 3
4 5 6
7 8 9

The normal of the given matrix is = 16
Trace of the matrix is = 15

Run 2

Enter the order of the matrix
2*2

Enter the n coefficients of the matrix
2 4
6 8

The normal of the given matrix is = 10

Trace of the matrix                       = 10