Java教程

Java确定两个矩阵是否相等

确定两个矩阵是否相等的Java程序

在此程序中,我们需要检查给定的矩阵是否相等。
两个矩阵是当且仅当满足以下条件时,才表示相等:
两个矩阵的行和列数应相同。 两个矩阵都应具有相同的对应元素。 Java程序,以确定两个矩阵是否相等
考虑上面的示例,其中矩阵A和B相等,因为它们具有相同的大小和相同的对应元素。

算法

步骤1: START 步骤2: 定义row1,col1,row2,col2 步骤3: 初始化第一个矩阵a[][] = {{1,2,3},{8,4,6},{4,5,7}} 步骤4: 初始化第二个矩阵b [] [] = {{1,2,3},{8,4,6} {4,5,7}} 步骤5: row1 = a.length 步骤6: col1 = a [0].length 步骤7: row2 = b.length 步骤8: col2 = b [0].length 步骤9: if(row1!= row2 || col1!= col2)
然后
PRINT "No"
否则
转到步骤10;
步骤10: 直到i < row1
重复步骤11 ////((i = 0; i < row1; i ++)
步骤11: 重复步骤12直到j < col1
////for(j = 0; j < col1; j++)
步骤12: if(a[i][j] = b [i][j]) 则
flag = false
break
步骤13: if(flag)
then PRINT" Yes"
else
PRINT" No"
步骤14: END

程序

public class EqualMatrix
{
    public static void main(String[] args) {
        int row1, col1, row2, col2;
        boolean flag = true;
        //Initialize matrix a
        int a[][] = {
            {1, 2, 3},
            {8, 4, 6},
            {4, 5, 7}
        };
        //Initialize matrix b
        int b[][] = {
            {1, 2, 3},
            {8, 4, 6},
            {4, 5, 7}
        };
        //Calculates the number of rows and columns present in the first matrix
          row1 = a.length;
        col1 = a[0].length;
        //Calculates the number of rows and columns present in the second matrix
          row2 = b.length;
        col2 = b[0].length;
        //Checks if dimensions of both the matrices are equal
        if(row1 != row2 || col1 != col2){
            System.out.println("Matrices are not equal");
        }
        else {
            for(int i = 0;i <row1;i++){
                for(int j = 0;j <col1;j++){
                    if(a[i][j] != b[i][j]){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag)
                System.out.println("Matrices are equal");
            else
                System.out.println("Matrices are not equal");
        }
    }
}
输出:
Matrices are equal
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4