Java - 添加矩阵 - 错误

时间:2014-01-17 03:23:08

标签: java matrix addition

代码:

  public static void main(String[] args) {
  int m, n, p, q, c, d, k;
  int sum1 = 0;

  Scanner scan = new Scanner(System.in); 

  System.out.println("Please enter the number of rows and columns for the first     matrix.");
  m = scan.nextInt();
  n = scan.nextInt();

  int first[][] = new int[m][n];

  System.out.println("Enter the elements of first matrix:"); 

  for ( c = 0 ; c < m ; c++ ) // The numbers are put into the matrix.
     for ( d = 0 ; d < n ; d++ )
        first[c][d] = scan.nextInt();

  System.out.println("Please enter the number of rows and columns for the second matrix."); 
  p = scan.nextInt();
  q = scan.nextInt();


  int second[][] = new int[p][q];
  int multiply[][] = new int[m][q];
  int sum[][] = new int[m][n]; 

  System.out.println("Enter the elements of second matrix:");

  for ( c = 0 ; c < p ; c++ )    
     for ( d = 0 ; d < q ; d++ )
        second[c][d] = scan.nextInt();


  for ( c = 0 ; c < m ; c++ )  
  {
     for ( d = 0 ; d < q ; d++ )
     {   
        for ( k = 0 ; k < p ; k++ )
        {
           sum1 = sum1 + first[c][k]*second[k][d]; 
        }
        multiply[c][d] = sum1;
        sum1 = 0;
     }
  }

  System.out.println("The product of the two matrices is: ");  
  for ( c = 0 ; c < m ; c++ ) {
     for ( d = 0 ; d < q ; d++ ) {
        System.out.print(multiply[c][d]+"\t");
     }

     System.out.print("\n");

  }

  for ( c = 0 ; c < m ; c++ )   { 
     for ( d = 0 ; d < n ; d++ ) {
        sum[c][d] = first[c][d] + second[c][d];    


        System.out.println("The sum of the two matrices is: "); 
        for ( c = 0 ; c < m ; c++ )
        {
           for ( d = 0 ; d < n ; d++ )
              System.out.print(sum[c][d]+"\t");

           System.out.println();

        }
     }
  }
  }
  }

总和的输出不正确。打印方式如下:
两个矩阵的总和是:
0 0
0 0

任何人都知道如何解决这个问题?

我一直试图解决这个问题,但最终得到了更多错误。抱歉所有的问题,我是初学者。谢谢:))

1 个答案:

答案 0 :(得分:2)

代码的一个问题是打印求和矩阵的循环位于循环内部,用于求和矩阵。请注意,当打印循环退出时,cd将分别为mn,因此外部循环将立即退出。稍后在代码中移动打印循环。

所以不要这样:

for ( c = 0 ; c < m ; c++ )   { 
    for ( d = 0 ; d < n ; d++ ) {
        sum[c][d] = first[c][d] + second[c][d];    


        System.out.println("The sum of the two matrices is: "); 
        for ( c = 0 ; c < m ; c++ )
        {
           for ( d = 0 ; d < n ; d++ )
              System.out.print(sum[c][d]+"\t");

           System.out.println();

        }
    }
}

使用它:

for ( c = 0 ; c < m ; c++ )   { 
    for ( d = 0 ; d < n ; d++ ) {
        sum[c][d] = first[c][d] + second[c][d];    
    }
}
System.out.println("The sum of the two matrices is: "); 
for ( c = 0 ; c < m ; c++ ) {
    for ( d = 0 ; d < n ; d++ )
        System.out.print(sum[c][d]+"\t");
    System.out.println();
}