如何在Java中格式化矩阵乘法

问题描述 投票:0回答:1

因此,在我的家庭作业的这一部分中,我需要做矩阵乘法,这是一般准则:

enter image description here

就计算而言,我没问题,但是我的教授说,如果组件中的任何double为.00,则必须将其表示为整数,例如a(ij)= a(13)中的24 = 24,如您在作业示例中看到的那样。但是,就我而言,无论我如何尝试,都不能不舍弃小数格式而将其设置为24的整数。

此外,当我打印出结果时,我从最后一行输出开始,从新的一行开始:“矩阵的乘法是:”

而作业示例在输出的同一行上显示了相乘矩阵的第一行,并为接下来的行完美地设置了格式。

有人请帮助。我不知道为什么我的教授为什么对功能设计如此严格,但是我试图解决这个问题已经有几个小时了,但我被困住了。

enter image description here

import java.text.DecimalFormat;

import java.util.Scanner;


public class ProblemFour {


public static void main(String[] args){

    System.out.print("Enter matrix1: ");

    Scanner stdin = new Scanner(System.in);

    String a = stdin.nextLine();

    System.out.print("Enter matrix2: ");

    String b = stdin.nextLine();

    ProblemFour o = new ProblemFour();

    double[][] matrixA = new double[3][3];
    double[][] matrixB = new double[3][3];


    String[] nums1 = a.split(" ");
    String[] nums2 = b.split(" ");

    if(nums1.length == nums2.length){
        matrixA = o.makeMatrix(nums1);
        matrixB = o.makeMatrix(nums2);
        double[][] matrixC = o.multiplyMatrix(matrixA, matrixB);

        for(int i =0; i<3; i++){
            System.out.println(" ");
            if(i==0){
                System.out.println("Multiplication of the matrices is: ");
            }
            System.out.println(" ");
            for(int j=0; j<3; j++){
                System.out.print(matrixC[i][j] + " ");
            }


        }


    }else{
        System.out.println("matrix1 column not equal to matrix2 row");
        stdin.close();
    }


}

public double[][] makeMatrix(String[] nums){
    double[][] matrix = new double[3][3];
    for(int i=0; i<matrix.length; i++){
        for(int j=0; j<matrix[0].length; j++){

            int n = matrix[j].length*i +j;
            matrix[i][j] = Double.parseDouble(nums[n]);

        }
    }
    return matrix;
}


public static double[][] multiplyMatrix(double[][]a, double[][]b){
    double totalElem = 0.0;
    double[][] multipliedMatrix = new double[3][3];
    for(int i=0; i<3; i++){
        for(int j=0; j<3; j++){
            for(int k=0; k<3; k++){
                DecimalFormat df = new DecimalFormat("##.#");
                double current = a[i][k] * b[k][j];
                double newdf = Double.parseDouble(df.format(current));

                totalElem += newdf;
                if(k==2){
                    int roundInt = (int)totalElem;

                    if(totalElem-roundInt==0.0){
                        multipliedMatrix[i][j] = roundInt;
                    }
                    else{
                        multipliedMatrix[i][j] = totalElem;
                    }
                    totalElem=0;
                }
            }
        }
    }
    return multipliedMatrix;

}

}
java performance oop matrix-multiplication design
1个回答
0
投票

让我们为您提供线索

© www.soinside.com 2019 - 2024. All rights reserved.