Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ตัวดำเนินการเชิงสัมพันธ์และตรรกะในภาษา C

ตัวดำเนินการเชิงสัมพันธ์ (Relational Operators)

ใช้เปรียบเทียบค่าสองค่า คืนค่า 1 หากจริง, 0 หากเท็จ

ตัวดำเนินการชื่อ
==Equal to
>Greater than
<Less than
!=Not equal to
>=Greater than or equal to
<=Less than or equal to

ตัวอย่าง

#include <stdio.h>
int main() {
    int x = 10, y = 28;
    if (x == y) printf("Both variables are equal\n");
    if (x > y) printf("x is greater than y\n");
    if (x < y) printf("x is less than y\n");
    if (x != y) printf("x is not equal to y\n");
    if (x <= y) printf("x is lesser or equal to y\n");
    if (x >= y) printf("x is greater or equal to y\n");
    return 0;
}

ผลลัพธ์

x is less than y
x is not equal to y
x is lesser or equal to y

ตัวดำเนินการตรรกะ (Logical Operators)

ใช้ทำงานเชิงตรรกะ คืนค่า 0 หรือ 1 ใช้ในการตัดสินใจ

ตัวดำเนินการความหมายผลลัพธ์
&&Logical ANDจริงเมื่อทุก operand จริง
||Logical ORจริงถ้ามี operand อย่างน้อยหนึ่งจริง
!Logical NOTจริงเมื่อ operand เป็นศูนย์

ตัวอย่าง

#include <stdio.h>
int main() {
    int x = 10, y = 28, a = 15, b = 20;
    if (x < y && a == b) printf("x is less than y AND a is equal to b\n");
    if (x < y || a == b) printf("x is less than y OR a is equal to b\n");
    if (!x) printf("x is zero\n");
    return 0;
}

ผลลัพธ์

x is less than y OR a is equal to b