หากต้องการตรวจสอบว่าจำนวนนั้นหารด้วย 2 ลงตัวหรือไม่ คุณต้องหาเศษที่เหลือก่อน
หากเศษของจำนวนที่หารด้วย 2 เป็น 0 ก็จะหารด้วย 2 ลงตัว
สมมติว่าจำนวนของเราคือ 10 เราจะตรวจสอบโดยใช้ 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 = 10;
// 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();
}
}
} ผลลัพธ์
Divisible by 2