簡體   English   中英

使用Java的平方矩陣乘法

[英]Square Matrix multiplication using Java

我正在嘗試編寫一個使用多維數組的簡單方陣乘法方法。

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

有人可以告訴我這段代碼有什么問題嗎?

問題在這里:

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演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM