用户必须输入两个矩阵的顺序以及两个矩阵的元素。然后,比较这两个矩阵。
如果矩阵元素和大小都相等,则表明两个矩阵相等。
如果矩阵大小相等但元素相等不相等,则显示矩阵可以比较,但不相等。
如果大小和元素不匹配,则显示矩阵无法比较。
程序以下是c程序,用于比较两个矩阵是否相等 -
#include <stdio.h>#include <conio.h>main(){ int a[10][10], b[10][10]; int i, j, r1, c1, r2, c2, flag =1; printf("enter the order of the matrix a
"); scanf("%d %d", &r1, &c1); printf("enter the order of the matrix b
"); scanf("%d %d", &r2,&c2); printf("enter the elements of matrix a
"); for(i=0; i<r1; i++){ for(j=0; j<c1; j++){ scanf("%d",&a[i][j]); } } printf("enter the elements of matrix b
"); for(i=0; i<r2; i++){ for(j=0; j<c2; j++){ scanf("%d",&b[i][j]); } } printf("matrix a is
"); for(i=0; i<r1; i++){ for(j=0; j<c1; j++){ printf("%3d",a[i][j]); } printf("
"); } printf("matrix b is
"); for(i=0; i<r2; i++){ for(j=0; j<c2; j++){ printf("%3d",b[i][j]); } printf("
"); } /* comparing two matrices for equality */ if(r1 == r2 && c1 == c2){ printf("matrices can be compared
"); for(i=0; i<r1; i++){ for(j=0; j<c2; j++){ if(a[i][j] != b[i][j]){ flag = 0; break; } } } } else{ printf(" cannot be compared
"); exit(1); } if(flag == 1 ) printf("two matrices are equal
"); else printf("but,two matrices are not equal
");}
输出当执行上述程序时,会产生以下结果 -
run 1:enter the order of the matrix a2 2enter the order of the matrix b2 2enter the elements of matrix a1234enter the elements of matrix b1234matrix a is 1 2 3 4matrix b is 1 2 3 4matrices can be comparedtwo matrices are equalrun 2:enter the order of the matrix a2 2enter the order of the matrix b2 2enter the elements of matrix a1234enter the elements of matrix b5678matrix a is 1 2 3 4matrix b is 5 6 7 8matrices can be comparedbut,two matrices are not equal
以上就是c程序用于比较两个矩阵是否相等的详细内容。