java中使得两个矩阵相,Java程序检查两个给定矩阵是否相同

如果两个矩阵的行数和列数相等并且相应的元素也相等,则它们是相同的。一个例子如下。Matrix A =

1 2 3

4 5 6

7 8 9

Matrix B =

1 2 3

4 5 6

7 8 9

The matrices A and B are identical

给出了一个检查两个矩阵是否相同的程序,如下所示。

示例public class Example {

public static void main (String[] args) {

int A[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };

int B[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };

int flag = 1;

int n = 3;

for (int i = 0; i 

for (int j = 0; j 

if (A[i][j] != B[i][j])

flag = 0;

if (flag == 1)

System.out.print("Both the matrices are identical");

else

System.out.print("Both the matrices are not identical");

}

}

输出结果Both the matrices are identical

现在让我们了解上面的程序。

定义了两个矩阵A和B。flag的初始值为1。然后使用嵌套的for循环比较两个矩阵的每个元素。如果任何对应的元素不相等,则将flag的值设置为0。证明这一点的代码段如下所示-int A[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };

int B[][] = { {7, 9, 2}, {3, 8, 6}, {1, 4, 2} };

int flag = 1;

int n = 3;

for (int i = 0; i 

for (int j = 0; j 

if (A[i][j] != B[i][j])

flag = 0;

如果flag为1,则矩阵相同,并显示出来。否则,矩阵不相同,将显示出来。证明这一点的代码片段如下所示-if (flag == 1)

System.out.print("Both the matrices are identical");

else

System.out.print("Both the matrices are not identical");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值