C# มีประเภทข้อมูลตัวเลขหลายแบบ สำหรับจำนวนเต็มใช้ int (32-bit signed integer) เป็นหลัก
ประเภทตัวเลขพื้นฐาน
| ประเภท | ขนาด | ช่วงค่าประมาณ |
|---|---|---|
byte | 8-bit | 0 ถึง 255 |
short | 16-bit | -32,768 ถึง 32,767 |
int | 32-bit | -2.1B ถึง 2.1B |
long | 64-bit | -9.2E18 ถึง 9.2E18 |
float | 32-bit | 7 หลักสำคัญ |
double | 64-bit | 15-16 หลักสำคัญ |
decimal | 128-bit | 28-29 หลักสำคัญ (เหมาะสำหรับการเงิน) |
ลำดับความสำคัญของตัวดำเนินการ (Operator Precedence)
ตัวดำเนินการที่มี Precedence สูงกว่าจะถูกประเมินก่อน
// ตัวอย่าง
int x = 9 + 2 * 5; // x = 19 ไม่ใช่ 55
// 2 * 5 คำนวณก่อน (Precedence สูงกว่า +) แล้วค่อย + 9
ลำดับ Precedence (จากสูงไปต่ำ)
()วงเล็บ++ -- ! ~Unary operators* / %คูณ หาร โมดולอ+ -บวก ลบ< <= > >=เปรียบเทียบ== !=เท่ากับ ไม่เท่ากับ&&AND ตรรกะ||OR ตรรกะ?:Ternary= += -= ...Assignment
ตัวอย่างการคำนวณกับ Precedence
using System;
class Program {
static void Main() {
int a = 200, b = 100, c = 150, d = 50;
int res;
res = (a + b) * c / d; // (300) * 150 / 50 = 900
Console.WriteLine("(a + b) * c / d = {0}", res);
res = ((a + b) * c) / d; // เหมือนข้างบน (ชัดเจนกว่า)
Console.WriteLine("((a + b) * c) / d = {0}", res);
res = (a + b) * (c / d); // 300 * (3) = 900
Console.WriteLine("(a + b) * (c / d) = {0}", res);
res = a + (b * c) / d; // 200 + (15000/50) = 500
Console.WriteLine("a + (b * c) / d = {0}", res);
Console.ReadLine();
}
}
แนวทางปฏิบัติ
- ใช้วงเล็บ
()เพื่อระบุลำดับการคำนวณให้ชัดเจน - หลีกเลี่ยงพึ่งพา Precedence อย่างเดียว โค้ดจะอ่านง่ายขึ้น
- ใช้
decimalสำหรับการคำนวณทางการเงินเพื่อความแม่นยำ