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

ตรวจสอบเลขหาร 2 ลงตัวใน C#

ภาพรวม

ใช้ Modulo operator (%) ตรวจสอบเศษ หาร 2 ลงตัว = เลขคู่ (Even number)

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


using System;

namespace Demo {
    class Test {
        static void Main(string[] args) {
            int num = 18;

            if (num % 2 == 0) {
                Console.WriteLine("Divisible by 2 (Even number)");
            } else {
                Console.WriteLine("Not divisible by 2 (Odd number)");
            }

            Console.ReadLine();
        }
    }
}

ผลลัพธ์


Divisible by 2 (Even number)

วิธีอื่นๆ

1. Bitwise AND (เร็วกว่าเล็กน้อย)


if ((num & 1) == 0) {
    Console.WriteLine("Even");
} else {
    Console.WriteLine("Odd");
}

ทำงานเพราะเลขคู่มี LSB = 0, เลขคี่มี LSB = 1

2. ใช้ Math.DivRem (ได้ทั้งผลหารและเศษ)


int quotient = Math.DivRem(num, 2, out int remainder);
if (remainder == 0) Console.WriteLine("Even");

3. Extension Method (สวยงาม)


public static class IntExtensions {
    public static bool IsEven(this int n) => (n & 1) == 0;
    public static bool IsOdd(this int n) => (n & 1) != 0;
}

// ใช้งาน
if (num.IsEven()) Console.WriteLine("Even");

การใช้งานจริง


// กรองเลขคู่จากลิสต์
var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evens = numbers.Where(n => n % 2 == 0).ToArray();
// Result: [2, 4, 6, 8, 10]

// แยกคู่/คี่
var (even, odd) = numbers.Partition(n => n % 2 == 0); // ต้องมี MoreLINQ หรือเขียนเอง

ข้อควรระวัง

  • Modulo กับเลขลบ: -3 % 2 == -1 ใน C# (ไม่ใช่ 1) แต่ (-3 & 1) == 1 ทำงานถูกต้อง
  • Bitwise เร็วกว่า Modulo ในระดับ low-level แต่ Compiler มัก optimize ให้เหมือนกัน
  • ใช้ IsEven/IsOdd extension method เพื่อ readability