1. your-netid_hw5_1.java : Liang page 253, programming exercise 7.6.
(Multiplying two matrices) Write a method to multiply two matrices. The header of the method is as follows:
public static double[][] multiplyMatrix(double[][] a, double[][] b)
To multiply matrix a by matrix b, the number of columns in a must be the same as the number of rows in b, and the two matrices must have elements of the same or compatible types. Let c be the result of the multiplication. Each element cij is ai1 x b1j + ai2 x b2j + … + ain x bnj.
Write a test program that prompts the user to enter tow 3 x 3 matrices and displays their product.
So this was the homework problem, and this is the code I have. And it works. The only problem is the output needs to be rounded, I don't know how to do that. Help???
import java.util.Scanner;
public class MultiplyMatrix {
public static void main(String[]args){
System.out.println("Enter numbers continuously for a 3 x 3 matrix: ");
Scanner input = new Scanner(System.in);
double [][] matrix1 = new double[3][3];
for (int r = 0; r < 3; r++)
{
for (int c = 0; c < 3; c++)
{
System.out.print("Enter a number: ");
matrix1[r][c] = input.nextDouble();
}
}
System.out.println("Now enter numbers continuously for second 3 x 3 matrix: ");
double [][] matrix2 = new double [3][3];
for (int g = 0; g < 3; g++)
{
for (int d = 0; d < 3; d++)
{
System.out.print("Enter a number: ");
matrix2[g][d] = input.nextDouble();
}
}
multiply(matrix1, matrix2);
}
public static double[][] multiply(double a[][], double b[][]) {
int m1rows = a.length;
int m1cols = a[0].length;
int m2cols = b[0].length;
double[][] result = new double[m1rows][m2cols];
for (int i=0; i<m1rows; i++)
for (int j=0; j<m2cols; j++)
for (int k=0; k<m1cols; k++){
result[i][j] += a[i][k] * b[k][j];
}
printMatrix(result);
return result;
}
static void printMatrix(double[][] mat) {
int M = mat.length;
int N = mat[0].length;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print( mat[i][j] + " ");
}
System.out.println();
}
}
}
The test problem asks you to input
1 2 3
4 5 6
7 8 9
and
0 2 4
1 4.5 2.2
1.1 4.3 5.3
This is what it outputs:
5.300000000000001 23.9 24.0
11.600000000000001 56.3 58.2
17.9 88.69999999999999 92.4
How can i round those values????