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

โปรแกรม C# ตรวจสอบเลขหาร 2 ลงตัว

ในการตรวจสอบว่าเลขหาร 2 ลงตัวหรือไม่ ให้หาเศษจากการหารด้วย 2

ถ้าเศษเป็น 0 = หาร 2 ลงตัว

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

ตัวอย่าง

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo {
    class MyApplication {
        static void Main(string[] args) {
            int num = 10;
            if (num % 2 == 0) {
                Console.WriteLine("Divisible by 2");
            } else {
                Console.WriteLine("Not divisible by 2");
            }
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Divisible by 2