Relational Operators
ใช้เปรียบเทียบค่าในตัวแปร 2 ตัว กำหนดความสัมพันธ์ระหว่างกัน
| Operator | Description |
|---|---|
| > | Greater than (มากกว่า) |
| >= | Greater than or equal to (มากกว่าหรือเท่ากับ) |
| <= | Less than or equal to (น้อยกว่าหรือเท่ากับ) |
| < | Less than (น้อยกว่า) |
ใช้ใน conditional statements และ loops เพื่อตรวจสอบความสัมพันธ์
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int a = 3, b = 2;
if (a < b) {
cout << a << " is less than " << b;
} else if (a > b) {
cout << a << " is greater than " << b;
}
return 0;
}
ผลลัพธ์
3 is greater than 2
Equality Operators
== (equal to) และ != (not equal to) precedence ต่ำกว่า relational operators ผลลัพธ์เป็น bool
==คืน true ถ้าค่าเท่ากัน!=คืน true ถ้าค่าไม่เท่ากัน
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
cout << boolalpha
<< "The true expression 3 != 2 yields: "
<< (3 != 2) << endl
<< "The false expression 20 == 10 yields: "
<< (20 == 10) << endl;
}
ผลลัพธ์
The true expression 3 != 2 yields: true The false expression 20 == 10 yields: false