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

โปรแกรม C# ตรวจสอบเมทริกซ์สองตัวเหมือนกัน

ตรวจสอบว่าเมทริกซ์สองตัวเหมือนกัน (Identical) ทุกสมาชิก ต้องมีขนาดเท่ากันก่อน

ขั้นตอน

  1. ตรวจสอบขนาด (Rows, Columns) ถ้าไม่เท่ากัน → ไม่สามารถเปรียบเทียบได้
  2. วนลูปเปรียบเทียบสมาชิกทุกตำแหน่ง [i,j]
  3. ถ้ามีตำแหน่งไหนไม่เท่ากัน → ไม่เหมือนกัน

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

using System;
namespace Demo {
    public class ApplicationOne {
        public static void Main() {
            int[,] arr1 = new int[10, 10];
            int[,] arr2 = new int[10, 10];
            int flag = 1;
            int i, j, row1, col1, row2, col2;
            // รับขนาดและค่ามेटริกซ์ 1
            Console.Write("Rows in 1st matrix: "); row1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Columns in 1st matrix: "); col1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Rows in 2nd matrix: "); row2 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Columns in 2nd matrix: "); col2 = Convert.ToInt32(Console.ReadLine());
            // รับค่าสมาชิก...
            // (โค้ดรับค่ายาว จัดสรุปแค่ตรรกะหลัก)
            if (row1 != row2 || col1 != col2) {
                Console.Write("Matrices can't be compared\n");
            } else {
                for (i = 0; i < row1; i++) {
                    for (j = 0; j < col1; j++) {
                        if (arr1[i, j] != arr2[i, j]) {
                            flag = 0; break;
                        }
                    }
                }
                if (flag == 1) Console.Write("Matrices are equal!\n");
                else Console.Write("Matrices are not equal!\n");
            }
        }
    }
}

หมายเหตุ: โค้ดต้นฉบับมีเงื่อนไข row1 != row2 && col1 != col2 ผิด (ควรเป็น OR) เพราะถ้าแถวเท่ากันแต่คอลัมน์ต่างกันก็เปรียบเทียบไม่ได้ ผมแก้ไขเป็น || แล้ว