C 语言的简单程序:添加两个矩阵。结果是怎么回事?

Pol*_*gon 1 c matrix

我是新手。我正在尝试添加两个矩阵。
虽然代码对我来说似乎很简单,但结果令人困惑。
到底是怎么回事?

程序代码:

#include <stdio.h>

int main()
{
  int r, c, i, j;
  printf("This program will add two matrices.\n");

 //Determine the dimensions of the matrices 
 //(Matrix Addition stipulates that matrices have the same dimensions 
 // in order to be added.)
  printf("What dimensions are the matrices?\n");
  printf("Rows: ");
  scanf("%d", &r);
  printf("Columns: ");
  scanf("%d", &c);

  int matrixA[r][c], matrixB[r][c], matrixC[r][c];

  //take elements of Matrix A and print them as a matrix.
  printf("Enter the elements of the first matrix by row:\n");
    for(i=0; i<r; i++){
      printf("Row %d:\n", i+1);
      for(j=0; j<c; j++){
          scanf("%d", &matrixA[i][j]);
      }
  }
  printf("Matrix A: \n");
  for(i=0; i<r; i++){
      for(j=0; j<c; j++){
          printf("%d  ", matrixA[i][j]);
      }
      printf("\n");
  }

  //take elements of Matrix B and print them as a matrix.
  printf("Enter the elements of the second matrix by row:\n");
    for(i=0; i<r; i++){
      printf("Row %d:\n", i+1);
      for(j=0; j<c; j++){
          scanf("%d", &matrixA[i][j]);
      }
  }
  printf("Matrix B: \n");
  for(i=0; i<r; i++){
      for(j=0; j<c; j++){
          printf("%d  ", matrixA[i][j]);
      }
      printf("\n");
  }

  //Add the matrices, A + B = C.
  for(i=1; i<r; i++){
      for(j=1; j<c; j++){
          matrixC[i][j] = matrixA[i][j] + matrixB[i][j];
      }
  }

  //print matrix C.
   printf("A + B = C.\n");
   printf("Matrix C: \n");
   for(i=0; i<r; i++){
      for(j=0; j<c; j++){
          printf("%d  ", matrixC[i][j]);
      }
      printf("\n");
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

最终结果:

>This program will add two matrices.  
>What dimensions are the matrices?  
>Rows: 2  
>Columns: 2  
>Enter the elements of the first matrix by row:  
>Row 1:  
>1  
>2  
>Row 2:  
>3  
>4  
>Matrix A:  
>1  2    
>3  4    
>Enter the elements of the second matrix by row:  
>Row 1:  
>1  
>1  
>Row 2:  
>1  
>1  
>Matrix B:   
>1  1    
>1  1    
>A + B = C.  
>Matrix C:   
>4195760  0    
>-1978206811  32766    
Run Code Online (Sandbox Code Playgroud)

我承诺给这个 Matrix C 带来什么编程罪?
谢谢你的帮助。

旁白:在尝试发布这个问题时,我最初尝试使用块引用来格式化终端输出。虽然这看起来很合适并且给了我一个令人满意的预览,但由于以下错误,我无法发布:“您的帖子似乎包含未正确格式化为代码的代码。请使用代码工具栏按钮或 CTRL 将所有代码缩进 4 个空格+K 键盘快捷键。要获得更多编辑帮助,请单击 [?] 工具栏图标。” 因此,经过一些尝试更改帖子以满足机器的需求后,我发现如果我将终端输出格式化为代码,我会得到一个不同的错误:“看起来你的帖子主要是代码;请添加更多细节。” 因此,我发布了所有这些“Aside”以纠正第二个错误。我希望这个有点不相关的解释构成“

Era*_*lon 5

当您将它们相加时,您在两个循环中从 1 开始索引,因此某些矩阵 C 值是未初始化的垃圾值,您将其打印出来。

编辑:正如@ptb 指出的那样,您在矩阵 A 中读取了两次,而未初始化矩阵 B。