添加矩阵方法。双阵列。 Java的

时间:2013-11-20 03:30:01

标签: java matrix multidimensional-array

你必须添加矩阵。这不起作用,我不知道如何解决它! 我输入的两个矩阵如下所示。

当我输出代码时,我得到RAM中的位置而不是添加的矩阵。

我不确定它出了什么问题!我很感激帮助!谢谢! :d

public static double[][] add(double[][] a1, double [][] a2)
{  
    for (int r = 0; r<a1.length; r++)
    {
        for (int c = 0; c<a1[r].length; c++)
        {
            a1[r][c] = a1[r][c] + a2[r][c];
        }

    }
    return a1;
}

public static void main(String[] args)
{
    double [][] arr = {{1,3,4},
                               {2,0,1}};

    double [][] arr1 = {{0,0,2},
                                 {5,6,7}};

    System.out.println(Matrix.add(arr, arr1));
}

2 个答案:

答案 0 :(得分:3)

您正在数组上调用println,并且您看到数组返回的toString()。不要这样做。使用Arrays.deepToString(...)或使用for循环迭代数组打印出结果。

例如在伪代码中,

double[][] result = Matrix.add(...);
for go through rows
  for go through columns
    println the array item in the result array at row, column index

答案 1 :(得分:0)

您没有正确打印。试试这个(测试并运作):

public static double[][] add(double[][] a1, double [][] a2)
{  
    for (int r = 0; r<a1.length; r++)
    {
        for (int c = 0; c<a1[r].length; c++)
        {
            a1[r][c] = a1[r][c] + a2[r][c];
        }
    }
    return a1;
}

public static void main(String[] args) 
{
    double [][] arr1 = {{1,3,4},{2,0,1}};
    double [][] arr2 = {{0,0,2},{5,6,7}};
    double[][] sumMatrix = add(arr1,arr2);

    for (double r[] : sumMatrix)
    {
        for (double c : r)
            System.out.print(c + ", ");

        System.out.println("" + '\n');
    }
}