原文: https://www.programiz.com/c-programming/examples/add-matrix

在此示例中,您将学习使用二维数组在 C 编程中相加两个矩阵。

要理解此示例,您应该了解以下 C 编程主题:


相加两个矩阵的程序

  1. #include <stdio.h>
  2. int main() {
  3. int r, c, a[100][100], b[100][100], sum[100][100], i, j;
  4. printf("Enter the number of rows (between 1 and 100): ");
  5. scanf("%d", &r);
  6. printf("Enter the number of columns (between 1 and 100): ");
  7. scanf("%d", &c);
  8. printf("\nEnter elements of 1st matrix:\n");
  9. for (i = 0; i < r; ++i)
  10. for (j = 0; j < c; ++j) {
  11. printf("Enter element a%d%d: ", i + 1, j + 1);
  12. scanf("%d", &a[i][j]);
  13. }
  14. printf("Enter elements of 2nd matrix:\n");
  15. for (i = 0; i < r; ++i)
  16. for (j = 0; j < c; ++j) {
  17. printf("Enter element a%d%d: ", i + 1, j + 1);
  18. scanf("%d", &b[i][j]);
  19. }
  20. // adding two matrices
  21. for (i = 0; i < r; ++i)
  22. for (j = 0; j < c; ++j) {
  23. sum[i][j] = a[i][j] + b[i][j];
  24. }
  25. // printing the result
  26. printf("\nSum of two matrices: \n");
  27. for (i = 0; i < r; ++i)
  28. for (j = 0; j < c; ++j) {
  29. printf("%d ", sum[i][j]);
  30. if (j == c - 1) {
  31. printf("\n\n");
  32. }
  33. }
  34. return 0;
  35. }

输出

  1. Enter the number of rows (between 1 and 100): 2
  2. Enter the number of columns (between 1 and 100): 3
  3. Enter elements of 1st matrix:
  4. Enter element a11: 2
  5. Enter element a12: 3
  6. Enter element a13: 4
  7. Enter element a21: 5
  8. Enter element a22: 2
  9. Enter element a23: 3
  10. Enter elements of 2nd matrix:
  11. Enter element a11: -4
  12. Enter element a12: 5
  13. Enter element a13: 3
  14. Enter element a21: 5
  15. Enter element a22: 6
  16. Enter element a23: 3
  17. Sum of two matrices:
  18. -2 8 7
  19. 10 8 6

在此程序中,要求用户输入行数r和列数c。 然后,要求用户输入两个矩阵的元素(顺序r*c)。

然后,我们添加了两个矩阵的对应元素,并将其保存在另一个矩阵(二维数组)中。 最后,结果打印在屏幕上。