给定两个矩阵 MAT1[行][列] 和 MAT2[行][列],我们必须找到两个矩阵之间的差异并打印两个矩阵相减后获得的结果。两个矩阵相减为 MAT1[n][m] – MAT2[n][m]。
对于减法,两个矩阵的行数和列数应该相同。
Input: MAT1[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}} MAT2[N][N] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1}} Output: -8 -6 -4 -2 0 2 4 6 8
下面使用的方法如下 -
我们将为每一行和每一列迭代矩阵,并从 mat1[][] 中减去 mat2[][] 的值并将结果存储在 result[][] 中,其中所有矩阵的行和列保持相同。
In fucntion void subtract(int MAT1[][N], int MAT2[][N], int RESULT[][N]) Step 1-> Declare 2 integers i, j Step 2-> Loop For i = 0 and i < N and i++ Loop For j = 0 and j < N and j++ Set RESULT[i][j] as MAT1[i][j] - MAT2[i][j] In function int main() Step 1-> Declare a matrix MAT1[N][N] and MAT2[N][N] Step 2-> Call function subtract(MAT1, MAT2, RESULT); Step 3-> Print the result
实时演示
#include <stdio.h> #define N 3 // This function subtracts MAT2[][] from MAT1[][], and stores // the result in RESULT[][] void subtract(int MAT1[][N], int MAT2[][N], int RESULT[][N]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) RESULT[i][j] = MAT1[i][j] - MAT2[i][j]; } int main() { int MAT1[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int MAT2[N][N] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int RESULT[N][N]; // To store result int i, j; subtract(MAT1, MAT2, RESULT); printf("Resultant matrix is </p><p>"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", RESULT[i][j]); printf("</p><p>"); } return 0; }
如果运行上面的代码,它将生成以下输出 -
Resultant matrix is -8 -6 -4 -2 0 2 4 6 8
以上是C程序用于矩阵相减的详细内容。更多信息请关注PHP中文网其他相关文章!