统计信息

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

P6Q23

2008-04-17 23:20:11

天气: 晴朗 心情: 高兴

/*filename:P6Q23.java
 *Name:Wang Chaoran
 *Description:
23 (Adding two matrices)
Write a method to add two matrices. The header of the method is as follows:
public static int[][] addMatrix(int[][] a, int[][] b)
In order to be added, the two matrices must have the same dimensions and the same or compatible
types of elements. As shown below, two matrices are added by adding the two elements of the arrays with the same index:
*/
import java.util.Scanner;
class P6Q23{
  public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    System.out.println("Please input the dimention value for a (m x n) matris.\nPlease input m:");
    int m=scan.nextInt();
    System.out.println("Please input n:");
    int n=scan.nextInt();
    int[][] a = new int[n][m];
    int[][] b = new int[n][m];
    for(int i=0;i<a.length;i++){
      for(int j=0;j<a[i].length;j++){
        a[i][j]=(int)(Math.random()*10);
         b[i][j]=(int)(Math.random()*10);
      }
    }
    System.out.println("Matrix a:");
    print(a);
    System.out.println("Matrix b:");
    print(b);
    System.out.println("Add Matrix a,b: ");
    print(addMatrix(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[][] addMatrix(int[][] a,int[][] b){
    int[][] combine= new int[a.length][a[0].length];
    for(int i=0;i<a.length;i++)
      for(int j=0;j<a[i].length;j++)
      combine[i][j]=a[i][j]+b[i][j];
    return combine;
  }
}
加入收藏 编辑 审核

TAG: computing

我来说两句

OPEN

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