【问题标题】:Square Matrix multiplication using Java使用Java的方阵乘法
【发布时间】:2017-09-26 15:00:18
【问题描述】:

我正在尝试使用多维数组编写一个简单的方阵乘法方法。

package matrixmultiplication;

import java.util.Scanner;


public class Matrixmultiplication 
{
    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        int [][] a,b,c;
        int size;
        System.out.print("Enter the Size of the matrix :");
        size = scan.nextInt();
        a=b=c=new int[size][size];
        System.out.println("Enter the elements of the First matrix");
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            {
                System.out.print("Enter the element a[" + i +"]["+ j + "] : ");
                a[i][j] = scan.nextInt();
            }
        }
        System.out.println("Enter the elements of the Second matrix");
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            {
                System.out.print("Enter the element b[" + i +"]["+ j + "] : ");
                b[i][j] = scan.nextInt();
            }
        } 

        System.out.println("The Product of the two matrix is : ");
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            {
                int sum = 0;
                for(int k=0;k<size;k++)
                {
                    sum +=(a[i][k] * b[k][j]);
                }
                c[i][j] = sum;
                System.out.print(c[i][j] + "\t");
            }
            System.out.println();
        }         

    }

}

当我在 Netbeans 中运行这个程序时,我得到以下输出:

Enter the Size of the matrix :2
Enter the elements of the First matrix
Enter the element a[0][0] : 1
Enter the element a[0][1] : 1
Enter the element a[1][0] : 1
Enter the element a[1][1] : 1
Enter the elements of the Second matrix
Enter the element b[0][0] : 1
Enter the element b[0][1] : 1
Enter the element b[1][0] : 1
Enter the element b[1][1] : 1
The Product of the two matrix is : 
2   3   
3   10

这个程序的正确输出应该是:

2  2
2  2

谁能告诉我这段代码有什么问题。

【问题讨论】:

  • 你为什么不直接选择像jblas.org这样的现有库?

标签: java arrays matrix-multiplication


【解决方案1】:

问题出在这里:

a=b=c=new int[size][size];

这只会创建一个数组,并使所有变量都指向它。所以,更新c的元素也就是更新ab的元素。

改为创建 3 个数组:

a=new int[size][size];
b=new int[size][size];
c=new int[size][size];

Ideone demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2015-12-31
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    相关资源
    最近更新 更多