โอเปอเรเตอร์คือสัญลักษณ์ที่บอกให้คอมไพเลอร์ดำเนินการจัดการทางคณิตศาสตร์หรือตรรกะที่เฉพาะเจาะจง
| ตัวดำเนินการ | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| + | เพิ่มสองตัวถูกดำเนินการ | A + B =30 |
| - | ลบตัวถูกดำเนินการที่สองจากตัวแรก | A - B =-10 |
| * | คูณทั้งสองตัวถูกดำเนินการ | A * B =200 |
| / | แบ่งตัวเศษด้วยตัวลบ | B / A =2 |
| % | ตัวดำเนินการโมดูลัสและส่วนที่เหลือหลังการหารจำนวนเต็ม | B % A =0 |
| ++ | ตัวดำเนินการส่วนเพิ่มเพิ่มค่าจำนวนเต็มหนึ่งค่า | A++ =11 |
| -- | ตัวดำเนินการ Decrement ลดค่าจำนวนเต็มลงหนึ่งค่า | A-- =9 |
เรามาดูตัวอย่างการใช้ตัวดำเนินการเลขคณิตใน C#
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int a = 99;
int b = 33;
int c;
c = a + b;
Console.WriteLine("Value of c is {0}", c);
c = a - b;
Console.WriteLine("Value of c is {0}", c);
c = a * b;
Console.WriteLine("Value of c is {0}", c);
c = a / b;
Console.WriteLine("Value of c is {0}", c);
c = a % b;
Console.WriteLine("Value of c is {0}", c);
c = a++;
Console.WriteLine("Value of c is {0}", c);
c = a--;
Console.WriteLine("Value of c is {0}", c);
Console.ReadLine();
}
}
} ผลลัพธ์
Value of c is 132 Value of c is 66 Value of c is 3267 Value of c is 3 Value of c is 0 Value of c is 99 Value of c is 100