ตัวดำเนินการเลขคณิตพื้นฐานใน C# รวมถึงสิ่งต่อไปนี้ -
| ตัวดำเนินการ | คำอธิบาย |
|---|---|
| + | เพิ่มตัวถูกดำเนินการสองตัว |
| - | ลบตัวถูกดำเนินการที่สองออกจากตัวแรก |
| * | คูณทั้งสองตัวถูกดำเนินการ |
| / | แบ่งตัวเศษด้วย de-numerator |
| % | ตัวดำเนินการโมดูลัสและส่วนที่เหลือหลังการหารจำนวนเต็ม |
| ++ | ตัวดำเนินการส่วนเพิ่มจะเพิ่มค่าจำนวนเต็มทีละหนึ่ง |
| -- | ตัวดำเนินการลดจะลดค่าจำนวนเต็มลงหนึ่ง |
ในการเพิ่ม ให้ใช้ตัวดำเนินการเพิ่มเติม -
num1 + num2;
ในลักษณะเดียวกัน ใช้สำหรับการลบ การคูณ การหาร และตัวดำเนินการอื่นๆ
ตัวอย่าง
ให้เรามาดูตัวอย่างที่สมบูรณ์เพื่อเรียนรู้วิธีใช้ตัวดำเนินการเลขคณิตใน C#
using System;
namespace Sample {
class Demo {
static void Main(string[] args) {
int num1 = 50;
int num2 = 25;
int result;
result = num1 + num2;
Console.WriteLine("Value is {0}", result);
result = num1 - num2;
Console.WriteLine("Value is {0}", result);
result = num1 * num2;
Console.WriteLine("Value is {0}", result);
result = num1 / num2;
Console.WriteLine("Value is {0}", result);
result = num1 % num2;
Console.WriteLine("Value is {0}", result);
result = num1++;
Console.WriteLine("Value is {0}", result);
result = num1--;
Console.WriteLine("Value is {0}", result);
Console.ReadLine();
}
}
} ผลลัพธ์
Value is 75 Value is 25 Value is 1250 Value is 2 Value is 0 Value is 50 Value is 51