C++ มีตัวดำเนินการเลขคณิตพื้นฐาน 5 ตัว คือ:
- บวก (+)
- ลบ (-)
- หาร (/)
- คูณ (*)
- โมดูลอหรือเศษ (%)
ตัวอย่าง
ตัวดำเนินการเหล่านี้สามารถใช้งานกับการดำเนินการเลขคณิตใดๆ ใน C++ มาดูตัวอย่างกัน:
#include <iostream>
using namespace std;
int main() {
int a = 21;
int b = 10;
int c;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl;
c = a - b;
cout << "Line 2 - Value of c is :" << c << endl;
c = a * b;
cout << "Line 3 - Value of c is :" << c << endl;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl;
c = a % b;
cout << "Line 5 - Value of c is :" << c << endl;
return 0;
}
ผลลัพธ์
โค้ดนี้จะให้ผลลัพธ์ดังนี้:
Line 1 - Value of c is :31 Line 2 - Value of c is :11 Line 3 - Value of c is :210 Line 4 - Value of c is :2 Line 5 - Value of c is :1
ยังมี ตัวดำเนินการเลขคณิตแบบผสม (Compound Arithmetic Operators) ใน C++ อีกด้วย รูปแบบคือ e1 op= e2 โดยที่ e1 เป็น l-value ที่แก้ไขได้ ไม่ใช่ const และ e2 เป็นหนึ่งใน:
- ชนิดข้อมูลเลขคณิต
- pointer หาก op เป็น + หรือ -
รูปแบบ e1 op= e2 ทำงานเหมือน e1 = e1 op e2 แต่ e1 จะถูกประเมินค่าเพียงครั้งเดียว
ตัวดำเนินการเลขคณิตแบบผสมใน C++ มีดังนี้:
| ตัวดำเนินการ | คำอธิบาย |
|---|---|
| *= | คูณค่า operand ตัวแรกด้วยค่า operand ตัวที่สอง เก็บผลลัพธ์ใน object ที่ operand ตัวแรกระบุ |
| /= | หารค่า operand ตัวแรกด้วยค่า operand ตัวที่สอง เก็บผลลัพธ์ใน object ที่ operand ตัวแรกระบุ |
| %= | หา modulus ของ operand ตัวแรกด้วยค่า operand ตัวที่สอง เก็บผลลัพธ์ใน object ที่ operand ตัวแรกระบุ |
| += | บวกค่า operand ตัวที่สองเข้ากับ operand ตัวแรก เก็บผลลัพธ์ใน object ที่ operand ตัวแรกระบุ |
| -= | ลบค่า operand ตัวที่สองออกจาก operand ตัวแรก เก็บผลลัพธ์ใน object ที่ operand ตัวแรกระบุ |
มาดูตัวอย่างการใช้งานบางตัว:
#include <iostream>
using namespace std;
int main() {
int a = 3, b = 2;
a += b;
cout << a << endl;
a -= b;
cout << a << endl;
a *= b;
cout << a << endl;
a /= b;
cout << a << endl;
return 0;
}
ผลลัพธ์:
5 3 6 3
หมายเหตุ: การกำหนดค่าแบบผสมให้กับ enumerated type จะสร้างข้อความ error หาก left operand เป็น pointer type right operand ต้องเป็น pointer type หรือ constant expression ที่ประเมินค่าเป็น 0 หาก left operand เป็น integral type right operand ต้องไม่เป็น pointer type