21xrx.com
2024-04-20 04:04:07 Saturday
登录
文章检索 我的文章 写文章
Java中的矩阵加法
2021-07-08 17:54:07 深夜i     --     --
J a v a

Java 程序将两个任意顺序的矩阵相加。 您可以修改它以添加任意数量的矩阵。

 

Java中两个矩阵的相加

import java.util.Scanner;


class AddTwoMatrix
{
  public static void main(String args[])
  {
    int m, n, c, d;
    Scanner in = new Scanner(System.in);

    System.out.println("Enter the number of rows and columns of matrix");
    m = in.nextInt();
    n = in.nextInt();

    int first[][] = new int[m][n];
    int second[][] = new int[m][n];
    int sum[][] = new int[m][n];

    System.out.println("Enter the elements of first matrix");

    for (c = 0; c < m; c++)
      for (d = 0; d < n; d++)
        first[c][d] = in.nextInt();

    System.out.println("Enter the elements of second matrix");

    for (c = 0 ; c < m; c++)
      for (d = 0 ; d < n; d++)
        second[c][d] = in.nextInt();

    for (c = 0; c < m; c++)
      for (d = 0; d < n; d++)
        sum[c][d] = first[c][d] + second[c][d];  //replace '+' with '-' to subtract matrices

    System.out.println("Sum of the matrices:");

    for (c = 0; c < m; c++)
    {
      for (d = 0; d < n; d++)
        System.out.print(sum[c][d] + "\t");

      System.out.println();
    }
  }
}

 

下载添加矩阵程序类文件。

程序输出:

要添加两个以上的矩阵,您可以创建一个 Matrix 类,创建其对象,创建一个对这些对象求和的方法,然后使用循环调用该方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复