统计信息

  • 访问数:6136
  • 博客数:141
  • 建立时间:2008-01-05
  • 更新时间:2008-05-09
我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!

P6Q24

2008-04-18 06:32:22

天气: 晴朗 心情: 高兴

/*filename:P6Q24
 *Name:Wang Chaoran
 *Description:
Multiplying two matrices) Write a method to multiply two matrices. The header of the method is as follows:
public static int[][] multiplyMatrix(int[][] a, int[][] b)
--------------------------------------------------------------------------------
[Page 208]
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, and a,
b, and c are denoted as follows:
*/
import java.util.Scanner;
class P6Q24{
  public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    System.out.println("Please input the dimention value for first (m x n) matris.\nPlease input m:");
    int m=scan.nextInt();
    System.out.println("Please input n:");
    int n=scan.nextInt();
    System.out.println("Please input the dimention value for second (p x m) matrix.\nPlease input p:");
    int p=scan.nextInt();
    int[][] a = new int[n][m];
    int[][] b = new int[m][p];
    for(int i=0;i<a.length;i++){
      for(int j=0;j<a[i].length;j++){
        a[i][j]=(int)(Math.random()*10);
      }
      for(int k=0;k<b.length;k++){
       b[k][i]=(int)(Math.random()*10);
      }
    }
    System.out.println("Matrix a:");
    print(a);
    System.out.println("Matrix b:");
    print(b);
    System.out.println("Multiply Matrix a,b: ");
    print(multiplyMatrix(a,b));
  }
 
   public static void print(int[][] matrix){
    for(int i=0;i<matrix.length;i++){
      for(int j=0;j<matrix[i].length;j++)
        System.out.printf("%-5d",matrix[i][j]);
      System.out.println();
  }
    System.out.println();
}
   public static int[][] multiplyMatrix(int[][] a, int[][] b){
     int[][] combine=new int[a.length][b[0].length];
     for(int i=0;i<a.length;i++)
       for(int j=0;j<b[0].length;j++)
        for(int k=0;k<a[0].length;k++)
         combine[i][j]+=a[i][k]*b[k][j];
    
 
     return combine;
   }
  
}

 


加入收藏 编辑 审核

TAG: computing

我来说两句

OPEN

Powered by X-Space 1.2 © 2001-2006 Comsenz Technology Ltd