编写一个能进行矩阵乘法运算的程序。A×B,当A的列数和B的行数相同时,能进行矩阵运算。本程序的主类源文件(Test.java)已经创建好了,其中代码如下:
import java.util.Scanner;
public class Test {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("请输入矩阵A的行列数(空格间隔)");
int rowNum=sc.nextInt();
int colNum=sc.nextInt();
System.out.println("请逐行输入矩阵A的元素值(每输入一行回车一次,同一行相邻元素用空格分隔)");
double[][] arrA = inputArray(rowNum, colNum);
System.out.println("请输入矩阵B的行列数(空格间隔)");
rowNum=sc.nextInt();
colNum=sc.nextInt();
System.out.println("请逐行输入矩阵B的元素值(每输入一行回车一次,同一行相邻元素用空格分隔)");
double[][] arrB = inputArray(rowNum, colNum);
Matrix matA = new Matrix(arrA);
Matrix matB = new Matrix(arrB);
// 执行矩阵乘法,关于矩阵乘法的定义,请参考线性代数相关知识或百度查询
Matrix matC = matA.multiply(matB);
// 输出矩阵乘法的结果,注:这里实际上隐含着调用matC.toString(),因此,Matrix要定义toString方法,返回矩阵的字符串表示
System.out.println(matC);
Test.sc.close();
}
/**
* 输入一个二维数组,并返回这个数组的引用
*
* @param row 行数
* @param col 列数
* @return 数组的引用
*/
public static double[][] inputArray(int row, int col) {
double[][] a = new double[row][col];
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
a[r][c] = sc.nextDouble();
}
}
return a;
}
}
为了完成本关任务,你需要掌握:1.类的定义2.类的成员和对象的成员 3.矩阵相乘
![](https://i-blog.csdnimg.cn/blog_migrate/efe076bbcb4fe5f57667ab423b13c264.png)
![](https://i-blog.csdnimg.cn/blog_migrate/676519560ce36e34fbc31ff1dad1dcb4.png)
平台会对你编写的代码进行测试,以下是某个用例下的测试结果画面:请输入矩阵A的行列数(空格间隔)3 2请逐行输入矩阵A的元素值(每输入一行回车一次,同一行相邻元素用空格分隔)1 23 45 6请输入矩阵B的行列数(空格间隔)2 2请逐行输入矩阵B的元素值(每输入一行回车一次,同一行相邻元素用空格分隔)1.4 4534 0[[69.400 45.000 ][140.200 135.000 ][211.000 225.000 ]]
开始你的任务吧,祝你成功!
import java.text.DecimalFormat;
public class Matrix{
int row;
int col;
double[][] arr;
//Matrix构造方法
public Matrix(double[][] arr){
//获取arr的行列
this.row = arr.length;
this.col = arr[0].length;
this.arr = arr;
}
//两个矩阵乘积计算方法
public Matrix multiply(Matrix m){
if(this.col!= m.row){
return null;
}
double mul[][] = new double[this.row][m.col];
double temp = 0;
for(int i=0;i<this.row;i++){
for(int k=0;k<m.col;k++){
for(int j=0;j<this.col;j++){
temp += this.arr[i][j] * m.arr[j][k];
}
mul[i][k] = temp;
temp = 0;
}
}
Matrix result = new Matrix(mul);
return result;
}
//根据题目的输出要求,重写toString方法,此处请根据具体要求重写
public String toString() {
DecimalFormat df = new DecimalFormat("#.000");
String result = "[\n";
for(int i=0;i<this.row;i++){
result += "[";
for(int j=0;j<this.col;j++){
result += df.format(arr[i][j])+" ";
}
result += "]\n";
}
result += "]\n";
return result;
}
}
测试结果如下
![](https://i-blog.csdnimg.cn/blog_migrate/8debe64a12253889ec720f6512d5c726.png)