Реляційні та логічні оператори C ++ (з прикладами)

У цьому посібнику ми дізнаємося про реляційні та логічні оператори за допомогою прикладів.

У C ++ реляційні та логічні оператори порівнюють два або більше операндів і повертають trueабо falseзначення, або значення.

Ми використовуємо цих операторів для прийняття рішень.

Реляційні оператори C ++

Реляційний оператор використовується для перевірки зв'язку між двома операндами. Наприклад,

 // checks if a is greater than b a> b;

Ось >реляційний оператор. Він перевіряє, чи більше a ніж b, чи ні.

Якщо відношення істинне , воно повертає 1, тоді як якщо відношення хибне , воно повертає 0 .

Наступна таблиця узагальнює реляційні оператори, що використовуються в C ++.

Оператор Значення Приклад
== Дорівнює 3 == 5дає нам неправду
!= Не дорівнює 3 != 5дає нам правду
> Більше, ніж, величніше ніж, крутіший за 3> 5дає нам неправду
< Менше ніж 3 < 5дає нам правду
>= Більший або рівний 3>= 5дайте нам неправду
<= Менше або дорівнює 3 <= 5дає нам правду

== Оператор

==Повертається оператор, що дорівнює

  • true - якщо обидва операнди рівні або однакові
  • false - якщо операнди неоднакові

Наприклад,

 int x = 10; int y = 15; int z = 10; x == y // false x == z // true

Примітка: Реляційний оператор ==є не таким, як оператор присвоєння =. Оператор присвоєння =присвоює значення змінній, константі, масиву або вектору. Він не порівнює два операнди.

! = Оператор

!=Повертається не рівне оператору

  • true - якщо обидва операнди нерівні
  • false - якщо обидва операнди рівні.

Наприклад,

 int x = 10; int y = 15; int z = 10; x != y // true x != z // false

> Оператор

>Повертається оператор більше, ніж

  • true - якщо лівий операнд більший за правий
  • false - якщо лівий операнд менший за правий

Наприклад,

 int x = 10; int y = 15; x> y // false y> x // true

<Оператор

<Повертається оператор менше ніж

  • true - якщо лівий операнд менший за правий
  • false - якщо лівий операнд більший за правий

Наприклад,

 int x = 10; int y = 15; x < y // true y < x // false

> = Оператор

>=Повернення оператора більше або дорівнює

  • true - якщо лівий операнд більше або дорівнює правому
  • false - якщо лівий операнд менший за правий

Наприклад,

 int x = 10; int y = 15; int z = 10; x>= y // false y>= x // true z>= x // true

<= Оператор

<=Повернення оператора менше або дорівнює

  • true - якщо лівий операнд або менший, або дорівнює правому
  • false - якщо лівий операнд більший за правий

Наприклад,

 int x = 10; int y = 15; x> y // false y> x // true

Щоб дізнатись, як можна використовувати реляційні оператори зі рядками, зверніться до нашого підручника тут.

Логічні оператори C ++

Ми використовуємо логічні оператори, щоб перевірити, чи є вираз істинним чи хибним . Якщо вираз істинний , він повертає 1, тоді як якщо вираз хибний , він повертає 0 .

Оператор Приклад Значення
&& вираження1 && вираз 2 Логічне І.
true лише тоді, коли всі операнди істинні.
|| вираз1 || вираз 2 Logical OR.
true if at least one of the operands is true.
! !expression Logical NOT.
true only if the operand is false.

C++ Logical AND Operator

The logical AND operator && returns

  • true - if and only if all the operands are true.
  • false - if one or more operands are false.

Truth Table of && Operator

Let a and b be two operands. 0 represents false while 1 represents true. Then,

a b a && b
0 0 0
0 1 0
1 0 0
1 1 1

As we can see from the truth table above, the && operator returns true only if both a and b are true.

Note: The Logical AND operator && should not be confused with the Bitwise AND operator &.

Example 1: C++ OR Operator

 // C++ program demonstrating && operator truth table #include using namespace std; int main() ( int a = 5; int b = 9; // false && false = false cout < b)) << endl; // false && true = false cout << ((a == 0) && (a < b)) << endl; // true && false = false cout < b)) << endl; // true && true = true cout << ((a == 5) && (a < b)) << endl; return 0; )

Output

 0 0 0 1

In this program, we declare and initialize two int variables a and b with the values 5 and 9 respectively. We then print a logical expression

 ((a == 0) && (a> b))

Here, a == 0 evaluates to false as the value of a is 5. a> b is also false since the value of a is less than that of b. We then use the AND operator && to combine these two expressions.

From the truth table of && operator, we know that false && false (i.e. 0 && 0) results in an evaluation of false (0). This is the result we get in the output.

Similarly, we evaluate three other expressions that fully demonstrate the truth table of the && operator.

C++ Logical OR Operator

The logical OR operator || returns

  • true - if one or more of the operands are true.
  • false - if and only if all the operands are false.

Truth Table of || Operator

Let a and b be two operands. Then,

a b a || b
0 0 0
0 1 1
1 0 1
1 1 1

As we can see from the truth table above, the || operator returns false only if both a and b are false.

Example 2: C++ OR Operator

 // C++ program demonstrating || operator truth table #include using namespace std; int main() ( int a = 5; int b = 9; // false && false = false cout < b)) << endl; // false && true = true cout << ((a == 0) || (a < b)) << endl; // true && false = true cout < b)) << endl; // true && true = true cout << ((a == 5) || (a < b)) << endl; return 0; )

Output

 0 1 1 1

In this program, we declare and initialize two int variables a and b with the values 5 and 9 respectively. We then print a logical expression

 ((a == 0) || (a> b))

Here, a == 0 evaluates to false as the value of a is 5. a> b is also false since the value of a is less than that of b. We then use the OR operator || to combine these two expressions.

From the truth table of || operator, we know that false || false (i.e. 0 || 0) results in an evaluation of false (0). This is the result we get in the output.

Similarly, we evaluate three other expressions that fully demonstrate the truth table of || operator.

C++ Logical NOT Operator !

The logical NOT operator ! is a unary operator i.e. it takes only one operand.

It returns true when the operand is false, and false when the operand is true.

Таблиця правди! Оператор

Нехай а - операнд. Тоді,

Приклад 3: C ++! Оператор

 // C++ program demonstrating ! operator truth table #include using namespace std; int main() ( int a = 5; // !false = true cout << !(a == 0) << endl; // !true = false cout << !(a == 5) << endl; return 0; )

Вихідні дані

 1 0

У цій програмі ми оголошуємо та ініціалізуємо intзмінну a зі значенням 5. Потім ми друкуємо логічний вираз

 !(a == 0) 

Тут a == 0оцінюється falseяк значення a є 5. Однак ми використовуємо оператор NOT !на a == 0. Оскільки a == 0оцінює до false, !оператор інвертує результати, a == 0а кінцевий результат є true.

Подібним чином вираз !(a == 5)врешті повертається, falseоскільки a == 5є true.

Цікаві статті...