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

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

ถ้าผลหารของเลขหารด้วย 2 มีเศษเป็น 0 แสดงว่าเลขนั้นหาร 2 ลงตัว

// ตรวจสอบว่าเลขหาร 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;
            num = 5;
            // ตรวจสอบว่าเลขหาร 2 ลงตัวหรือไม่
            if (num % 2 == 0) {
                Console.WriteLine("Divisible by 2");
            } else {
                Console.WriteLine("Not divisible by 2");
            }
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Not divisible by 2

หลักการ: ใช้ตัวดำเนินการ Modulus (%) หาเศษจากการหาร หากเศษเป็น 0 แสดงว่าหารลงตัว