หากเศษที่เหลือเมื่อหารด้วย 2 เป็น 0 ก็จะหารด้วย 2 ลงตัว
สมมติว่าจำนวนของเราคือ 5 เราจะตรวจสอบโดยใช้ if-else ต่อไปนี้ -
// checking if the number is divisible by 2 or not
if (num % 2 == 0) {
Console.WriteLine("Divisible by 2 ");
} else {
Console.WriteLine("Not divisible by 2");
} ตัวอย่าง
ต่อไปนี้คือตัวอย่างเพื่อค้นหาว่าตัวเลขหารด้วย 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;
// checking if the number is divisible by 2 or not
if (num % 2 == 0) {
Console.WriteLine("Divisible by 2 ");
} else {
Console.WriteLine("Not divisible by 2");
}
Console.ReadLine();
}
}
} ผลลัพธ์
Not divisible by 2