importjavax.swing.JOptionPane;/***
实现两个矩阵相乘并将结果打印*@authorkillergsm**/publicclassMatrix{publicstaticvoidmain(String[]args){double[][]m1={{5,6,8,2},{8,4,5,...
import javax.swing.JOptionPane;
/**
*
实现两个矩阵相乘并将结果打印
* @author killergsm
*
*/
public class Matrix
{
public static void main(String[] args)
{
double[][] m1 =
{
{5,6,8,2},
{8,4,5,6},
{5,6,3,8}
};
double[][] m2 =
{
{5,6,9,8,7},
{5,2,3,6,9},
{9,9,5,4,7},
{3,2,5,1,4}
};
printMatrix(matrixMultiplication(m1,m2));
}
public static double[][] matrixMultiplication(double[][] m1,double[][] m2) //将两个矩阵相乘并返回结果
{
if(isMatrix(m1) == false || isMatrix(m2) == false
|| m1[0].length != m2.length) //如不符合相乘条件直接退出
return new double[0][0];
int x = m1.length;
int y = m1[0].length;
int z = m2[0].length;
int i = 0;
int xz = x*z;
double[][] m = new double[x][z];
for(;i < xz; i++)
{
m[i/z][i%z] = 0;
for(int j = 0; j < y; j++)
{
m[i/z][i%z] += m1[i/z][j] + m2[j][i%z];
}
}
return m;
}
public static boolean isMatrix(double[][] m) // 判断是否为矩阵
{
int i = m.length;
while(i > 1)
{
if(m[i-1].length != m[i-2].length);
return false;
i--;
}
return true;
}
public static void printMatrix(double[][] m) //打印矩阵
{
int i = 0;
int x = m.length;
int y = m[0].length;
int xy = x*y;
for(;i < xy;i++)
{
System.out.print(m[i/y][i%y] );
if(i%xy == y - 1)
System.out.println();
}
}
}
展开