Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C เปรียบเทียบเมทริกซ์สองตัวว่าเท่ากันหรือไม่


คำอธิบายปัญหา

รับขนาดและองค์ประกอบของเมทริกซ์ 2 ตัว มาเปรียบเทียบ:

  • ถ้าขนาดและองค์ประกอบเท่ากันทุกค่า → "Two matrices are equal"
  • ถ้าขนาดเท่ากันแต่องค์ประกอบต่างกัน → "Matrices can be compared but not equal"
  • ถ้าขนาดต่างกัน → "Cannot be compared"

โค้ดตัวอย่าง

#include <stdio.h>
#include <stdlib.h>

int main() {
    int A[10][10], B[10][10];
    int i, j, R1, C1, R2, C2, flag = 1;
    printf("Order of matrix A: "); scanf("%d %d", &R1, &C1);
    printf("Order of matrix B: "); scanf("%d %d", &R2, &C2);
    printf("Elements of A:\n");
    for (i = 0; i < R1; i++) for (j = 0; j < C1; j++) scanf("%d", &A[i][j]);
    printf("Elements of B:\n");
    for (i = 0; i < R2; i++) for (j = 0; j < C2; j++) scanf("%d", &B[i][j]);
    // แสดงเมทริกซ์ (略)
    if (R1 == R2 && C1 == C2) {
        printf("Matrices can be compared\n");
        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\n");
        exit(1);
    }
    if (flag) printf("Two matrices are equal\n");
    else printf("But, two matrices are not equal\n");
    return 0;
}

ผลลัพธ์ตัวอย่าง

Run 1: 2x2 matrices with same elements → Equal
Run 2: 2x2 matrices with different elements → Not equal