หากต้องการค้นหาว่าจำนวนนั้นหารด้วย 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 Test {
static void Main(string[] args) {
int num;
num = 18;
// 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