2006程式設計競賽第三題

題目:

Please write a program to multiply two
matrices. You have to write a function to input
two (4x4) matrices and output the multiplied
matrix.

程式碼:

/************************************************
*Please write a program to multiply two
*matrices. You have to write a function to input
*two (4x4) matrices and output the multiplied
*matrix. 
 ************************************************/
import java.util.*;
public class E2006_3{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
    
        int [][] arr = new int[4][4];//宣告4*4陣列
        int [][] numbers = new int[4][4];//宣告4*4陣列
        int [][] output = new int[4][4];
        for(int i=0; i<arr.length ; i++){
            System.out.print("Please input line "+(i+1)+" of first matrix:");
            for(int j=0; j<arr.length ;j++){
                arr[i][j] = sc.nextInt();
            }
        }
        
        for(int i=0; i<arr.length ; i++){
            System.out.print("Please input line "+(i+1)+" of second matrix:");
            for(int j=0; j<arr.length ;j++){
                numbers[i][j] = sc.nextInt();
            }
        }
        matrices(arr, numbers, output);
        print(output);
    }

    /*進行矩陣相乘 */
    public static void matrices(int [][] arr , int [][] arr1 ,int [][] arr2){
        for(int i=0;i<arr2.length;i++){
            for(int j=0;j<arr2[i].length;j++){
                arr2[i][j] = 0;
                for(int k=0; k<arr2[i].length ; k++)
                    arr2[i][j]=arr2[i][j]+arr[i][k]*arr1[k][j];
            }
        }   
    }
    /*印出答案 */
    public static void print(int arr[][]){
        System.out.println("The multiplied matrix is:");
        for(int[] result : arr){ 
            for(int result1 : result){
                System.out.print(result1+" ");
            }
            System.out.println();
        }
    } 
}
Ex
Please input line 1 of first matrix: 1 2 5 3
Please input line 2 of first matrix: 1 3 2 4
Please input line 3 of first matrix: 2 3 4 1
Please input line 4 of first matrix: 1 1 2 2
Please input line 1 of second matrix: 2 2 1 3
Please input line 2 of second matrix: 1 1 2 3
Please input line 3 of second matrix: 3 2 1 1
Please input line 4 of second matrix: 1 1 1 1
The multiplied matrix is:
22 17 13 17
15 13 13 18
20 16 13 20
11 9 7 10

心得:

矩陣相乘的原理,要清楚。

留言

熱門文章