//转载请注明出处:http://hi.baidu.com/jadmin/blog/item/163ed2f8a8e88b0dd8f9fd46.html
/**
* @(#)MatrixMultiply.java
*
*
* @author JAdmin
* @version 1.00 2007/8/21
*/
import java.util.Scanner;
public class MatrixMultiply
{
public static void main(String[] args)
{
int m,n,p;
System.out.println("请输入3个矩阵参数m,n,p.示例a[m][n]*b[n][p]=c[m][p]");
Scanner sr = new Scanner(System.in);
System.out.print("m=");
m = sr.nextInt();
System.out.print("n=");
n = sr.nextInt();
System.out.print("p=");
p = sr.nextInt();
int[][] a = new int[m][n];
int[][] b = new int[n][p];
int[][] c = new int[m][p];
System.out.println("请输入数组a[" + m + "][" + n + "]");
input(a);
System.out.println("请输入数组b[" + n + "][" + p + "]");
input(b);
//以下开始计算c[][]
for(int i = 0;i < c.length;i++)
for(int j = 0;j < c[0].length;j++)
c[i][j] = getMultiItem(a,b,i,j);
System.out.println("************The matrix a[][]************");
display(a);
System.out.println("************The matrix b[][]************");
display(b);
System.out.println("************The matrix c[][]************");
display(c);
}
private static void input(int[][] arr)
{
Scanner sr = new Scanner(System.in);
for(int i = 0;i < arr.length;i++)
for(int j = 0;j < arr[0].length;j++)
arr[i][j] = sr.nextInt();
}
private static void display(int[][] arr)
{
for(int i = 0;i < arr.length;i++)
{
for(int j = 0;j < arr[0].length;j++)
System.out.print(arr[i][j]+" ");
System.out.println();
}
}
private static int getMultiItem(int[][] a,int[][] b,int p,int q)
{
//计算元素c[p][q]
int tmp = 0;
for(int i = 0;i < a[0].length;i++)
tmp += a[p][i]*b[i][q];
return tmp;
}
}
posted on 2007-08-21 18:38
jadmin 阅读(59)
评论(0) 编辑 收藏