C 程式比較兩個矩陣是否相等
使用者必須輸入兩個矩陣的階數和元素。然後,對這兩個矩陣進行比較。
如果兩個矩陣元素及階數相等,則顯示這兩個矩陣相等。
如果矩陣階數相等,但元素不相等,則顯示可以對矩陣進行比較,但不相等。
如果階數和元素都不匹配,則顯示無法比較這些矩陣。
程式
以下是 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 A 2 2 Enter the order of the matrix B 2 2 Enter the elements of matrix A 1 2 3 4 Enter the elements of matrix B 1 2 3 4 MATRIX A is 1 2 3 4 MATRIX B is 1 2 3 4 Matrices can be compared Two matrices are equal Run 2: Enter the order of the matrix A 2 2 Enter the order of the matrix B 2 2 Enter the elements of matrix A 1 2 3 4 Enter the elements of matrix B 5 6 7 8 MATRIX A is 1 2 3 4 MATRIX B is 5 6 7 8 Matrices can be compared But,two matrices are not equal
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP