Introduction to Java Programming编程题7.6<两个矩阵相乘>

本文介绍如何在Java中实现两个矩阵的相乘操作,深入解析编程题7.6的相关算法与步骤,涵盖矩阵乘法的基本原理及其实现技巧。
/*
Enter matrix1: 1 2 3 4 5 6 7 8 9
Enter matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2
The mattrices are multiplied as follows:
5.3 23.9 24.0
11.6 56.3 58.2
17.9 88.7 92.4
 */
import java.util.Scanner;

public class MultMatrix {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int i, j, k;
        final int ROW = 3;
        final int COLUMN = 3;
        double[][] a = new double[ROW][COLUMN];
        double[][] b = new double[ROW][COLUMN];

        System.out.print("Enter matrix1: ");
        for (i = 0; i < ROW; i++)
            for (j = 0; j < COLUMN; j++)
                a[i][j] = input.nextDouble();

        System.out.print("Enter matrix2: ");
        for (i = 0; i < ROW; i++)
            for (j = 0; j < COLUMN; j++)
                b[i][j] = input.nextDouble();

        double[][] c = multiplyMatrix(a, b);
        System.out.println("The mattrices are multiplied as follows:");
        showMultiplayMatrix(c);
    }

    public static double[][] multiplyMatrix(double[][] a, double[][] b) {
        double[][] c = new double[a.length][a.length];
        for (int i = 0; i < a.length; i++)
            for (int j = 0; j < a.length; j++)
                c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];

        return c;
    }

    public static void showMultiplayMatrix(double[][] c) {
        for (int i = 0; i < c.length; i++) {
            for (int j = 0; j < c[i].length; j++)
                System.out.printf("%2.1f ", c[i][j]);
        System.out.println();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值