ตัวดำเนินการหาร / ใน C# ใช้หารตัวเลข สามารถใช้กับประเภทตัวเลขทั้งหมด (int, long, float, double, decimal) ผลลัพธ์ขึ้นอยู่กับประเภทของ Operand
พฤติกรรมสำคัญ: Integer Division
เมื่อหาร int / int ผลลัพธ์จะเป็น int (ตัดทศนิยมทิ้ง ไม่ใช่ปัดเศษ):
int a = 7, b = 2; int result = a / b; // 3 (ไม่ใช่ 3.5) double result2 = a / b; // 3.0 (หารเป็น int ก่อน แล้วค่อยแปลง) double result3 = (double)a / b; // 3.5 (แปลงก่อนหาร)
ตัวอย่างครบถ้วน: Arithmetic Operators
using System;
namespace Sample
{
class Demo
{
static void Main(string[] args)
{
int num1 = 50;
int num2 = 25;
int result;
result = num1 + num2;
Console.WriteLine($"บวก: {result}"); // 75
result = num1 - num2;
Console.WriteLine($"ลบ: {result}"); // 25
result = num1 * num2;
Console.WriteLine($"คูณ: {result}"); // 1250
result = num1 / num2;
Console.WriteLine($"หาร: {result}"); // 2
result = num1 % num2;
Console.WriteLine($"หารเอาเศษ: {result}"); // 0
result = num1++;
Console.WriteLine($"Post-increment: {result}"); // 50 (ค่าเดิม)
result = num1--;
Console.WriteLine($"Post-decrement: {result}"); // 51 (ค่าเดิม)
Console.ReadLine();
}
}
}
ผลลัพธ์
บวก: 75 ลบ: 25 คูณ: 1250 หาร: 2 หารเอาเศษ: 0 Post-increment: 50 Post-decrement: 51
ข้อควรระวัง
- หารด้วยศูนย์:
intโยนDivideByZeroException|float/double/decimalให้InfinityหรือNaN - Integer Division: ตัดทศนิยมทิ้งเสมอ ใช้
decimalหรือ Cast เป็นdoubleก่อนหาร - Overflow:
int.MinValue / -1โยน OverflowException (ใน checked context)
แนะนำสำหรับการเงิน
ใช้ decimal สำหรับการคำนวณเงิน:
decimal price = 19.99m; decimal quantity = 3; decimal total = price * quantity; // 59.97 - ไม่มี Floating Point Error