使用者必須輸入兩個矩陣的順序以及兩個矩陣的元素。然後,比較這兩個矩陣。
如果矩陣元素和大小都相等,則表示兩個矩陣相等。
如果矩陣大小相等但元素相等不相等,則顯示矩陣可以比較,但不相等。
如果大小和元素不匹配,則顯示矩陣無法比較。
以下是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</p><p>"); scanf("%d %d", &R1, &C1); printf("Enter the order of the matrix B</p><p>"); scanf("%d %d", &R2,&C2); printf("Enter the elements of matrix A</p><p>"); for(i=0; i<R1; i++){ for(j=0; j<C1; j++){ scanf("%d",&A[i][j]); } } printf("Enter the elements of matrix B</p><p>"); for(i=0; i<R2; i++){ for(j=0; j<C2; j++){ scanf("%d",&B[i][j]); } } printf("MATRIX A is</p><p>"); for(i=0; i<R1; i++){ for(j=0; j<C1; j++){ printf("%3d",A[i][j]); } printf("</p><p>"); } printf("MATRIX B is</p><p>"); for(i=0; i<R2; i++){ for(j=0; j<C2; j++){ printf("%3d",B[i][j]); } printf("</p><p>"); } /* Comparing two matrices for equality */ if(R1 == R2 && C1 == C2){ printf("Matrices can be compared</p><p>"); 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</p><p>"); exit(1); } if(flag == 1 ) printf("Two matrices are equal</p><p>"); else printf("But,two matrices are not equal</p><p>"); }
當執行上述程式時,會產生以下結果-
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
以上是C程式用於比較兩個矩陣是否相等的詳細內容。更多資訊請關注PHP中文網其他相關文章!