我试图通过使用两种不同的静态方法
来操纵两个数组double dot(double[]a, double[]b)
double[][] multiply(double[][]a, double[][]b)
。 我似乎无法弄清楚如何使用静态方法将两个数组相乘并将值输出给用户我相信我的Dot产品方法很好。我知道我需要为我的乘法方法使用return方法但我不确定如何正确表示
这是我到目前为止所做的:
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;
}
}
答案 0 :(得分: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]
答案 1 :(得分: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,
答案 2 :(得分:0)
在乘法方法中,第二个循环是错误的,j总是0,你应该返回c而不是
试试这个
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;
}