2

我正在尝试使用两种不同的静态方法来操作两个数组

  1. double dot(double[]a, double[]b)
  2. double[][] multiply(double[][]a, double[][]b).

我似乎无法弄清楚如何使用静态方法将两个数组相乘并将那里的值输出给用户我相信我的点积方法很好。我知道我的乘法方法需要使用返回方法,但我不确定如何正确表示

这是我到目前为止所拥有的:

public class LibMatrix {

    public static void main(String[] args) {

        double[] a = { 8, 5, 6, 3, 2, 1 };
        double[] b = { 9, 8, 4, 1, 4, 7 };
    }

    public static double dot(double[] a, double[] b) {
        double sum = 0.0;
        for (int i = 0; i < a.length; i++)
            sum += a[i] * b[i];
        return sum;

    }

    public static double[][] multiply(double[][] a, double[][] b) {
        int n = 6;
        double[][] c = new double[n][n];
        for (int i = 0; i < n; i++)
            for (int j = 0; i < n; i++)
                c[i][j] = a[i][j] * b[i][j];
        return a;

    }
}
4

3 回答 3

3

没有足够的代表发表评论,但您在第二种方法中的返回值应该是 c

测试:

double [][] a = new double [6][6];
double [][] b = new double [6][6];

for(int i = 0; i< a.length;i++){
    for(int j = 0; j< a.length;j++){
        a[i][j] = 3;
        b[i][j] = 2;
    }
}
d = multiply(a,b);

这将返回一个填充了 6s 的 6x6 矩阵,因此您的方法可以正常工作。

d = [6, 6, 6, 6, 6, 6,
     6, 6, 6, 6, 6, 6,
     6, 6, 6, 6, 6, 6,
     6, 6, 6, 6, 6, 6,
     6, 6, 6, 6, 6, 6,
     6, 6, 6, 6, 6, 6]
于 2013-02-27T17:34:50.217 回答
0

以下是一些更正:

public class LibMatrixTests
{
   static class LibMatrix {
      public static double dot(double[] a, double[] b) {
         double sum = 0.0;
         for (int i = 0; i < a.length; i++)
            sum += a[i] * b[i];
         return sum;
      }
      public static double[][] mul( double[][] a, double[][] b ) {
         double[][] c = new double[a.length][a[0].length];
         for (int i = 0; i < a.length; i++)
            for (int j = 0; j < a[i].length; j++)
               c[i][j] = a[i][j] * b[i][j];
         return a;
      }
   }

   public static void main( String[] args ) {
      double[]   a = { 8, 5, 6, 3, 2, 1 };
      double[]   b = { 9, 8, 4, 1, 4, 7 };
      double[][] c = { a, b };
      double[][] d = { b, a };
      double     e = LibMatrix.dot( a, b );
      double[][] f = LibMatrix.mul( c, d );
      System.out.println( e );
      for( double[] g : f ) {
         for( double h : g ) {
            System.out.print( h + ", " );
         }
         System.out.println();
      }
   }
}

输出:

154.0
8.0, 5.0, 6.0, 3.0, 2.0, 1.0, 
9.0, 8.0, 4.0, 1.0, 4.0, 7.0, 
于 2013-02-27T17:42:40.437 回答
0

在 multiply 方法中,第二个循环是错误的,j 总是 0,你应该返回 c 而不是 a

尝试这个

public static double[][] multiply(double[][] a, double[][] b) {
    int n = 6;
    double[][] c = new double[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            c[i][j] = a[i][j] * b[i][j];
    return c;

}
于 2013-02-27T17:50:12.320 回答