java从键盘输入两个3行3列的矩阵,计算两个矩阵的乘积并输出。
时间: 2023-04-06 07:03:40 浏览: 115
好的,这个问题可以回答。以下是Java代码:
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 输入第一个矩阵
System.out.print("Enter matrix1: ");
double[][] matrix1 = new double[3][3];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
matrix1[i][j] = input.nextDouble();
}
}
// 输入第二个矩阵
System.out.print("Enter matrix2: ");
double[][] matrix2 = new double[3][3];
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[i].length; j++) {
matrix2[i][j] = input.nextDouble();
}
}
// 计算矩阵乘积
double[][] resultMatrix = multiplyMatrix(matrix1, matrix2);
// 输出结果
System.out.println("The multiplication of the matrices is");
for (int i = 0; i < resultMatrix.length; i++) {
for (int j = 0; j < resultMatrix[i].length; j++) {
System.out.printf("%6.1f", resultMatrix[i][j]);
}
System.out.println();
}
}
public static double[][] multiplyMatrix(double[][] a, double[][] b) {
double[][] c = new double[a.length][b[0].length];
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[i].length; j++) {
for (int k = 0; k < a[i].length; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}
}
阅读全文