Зміст курсу
C++ Умовні оператори
C++ Умовні оператори
Вкладені оператори If
Вкладений оператор if
- це просто оператор if
всередині іншого оператора if
. Така структура дозволяє обчислювати декілька умов, одну за одною, і виконувати певні блоки коду. Зовнішній оператор if
виконує роль воріт, і на основі отриманих даних ворота можуть відкритись для іншого оператора if
всередині або ні.
nested_if
if (condition1) { // Code block 1 if (condition2) { // Code block 2 if (condition3) { // Code block 3 } } }
Consider a scenario where we want to determine a worker salary based on their performance.
main
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 17; int hours_worked = 37; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // And if the number of hours worked is more than 40 if (hours_worked > 40) { // add an additional 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } } std::cout << current_salary << std::endl; }
This code calculates an employee's new salary based on the number of completed tasks and hours worked, with a 20% increase if the tasks are over 15 and an additional 20% increase if hours worked are over 40. As you can see, the current calculations is 1200. And this can be achieved only by using nested if
statements, here some attempts to get same logic without them.
main
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 9; int hours_worked = 41; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } // If the number of hours worked is more than 40 if (hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } std::cout << current_salary << std::endl; }
At first it may seem that it works the same, but in this case the worker will receive an extra 20% raise, regardless of whether he has completed more than 15 tasks. Run the code and look at the output, it shows a value of 1200, even though this time the worker didn't completed more than 15 tasks.
main
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 19; int hours_worked = 39; // If the number of completed tasks is greater than 15 // AND the number of of hours worked is more than 40 if (completed_tasks > 15 && hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; std::cout << current_salary << std::endl; } std::cout << current_salary << std::endl; }
У цьому випадку може здатися, що він повинен працювати як задумано, але, на жаль, це також неправильно, результат буде 1000. Це тому, що якщо працівник виконає більше 15 завдань, але не відпрацює більше 40 годин, він нічого не отримає. Отже, нам необхідно використовувати вкладені оператори if
, щоб отримати правильну реалізацію.
Note
Nested
if
statements are necessary in some cases but not always. In the third section, we'll discuss when, why and how to avoid them.
Note
Nested
if
statements are necessary in some cases but not always. In the third section, we'll discuss when, why and how to avoid them.
Swipe to show code editor
We have an excess of pink phones in our inventory that we need to sell.
- Make a 20% discount on pink phones.
- If a phone's price exceeds $1,000, the discount will be reduced to 10%.
- For all other phones, increase the price by 10%.
Рішення
solution
Дякуємо за ваш відгук!
Вкладені оператори If
Вкладений оператор if
- це просто оператор if
всередині іншого оператора if
. Така структура дозволяє обчислювати декілька умов, одну за одною, і виконувати певні блоки коду. Зовнішній оператор if
виконує роль воріт, і на основі отриманих даних ворота можуть відкритись для іншого оператора if
всередині або ні.
nested_if
if (condition1) { // Code block 1 if (condition2) { // Code block 2 if (condition3) { // Code block 3 } } }
Consider a scenario where we want to determine a worker salary based on their performance.
main
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 17; int hours_worked = 37; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // And if the number of hours worked is more than 40 if (hours_worked > 40) { // add an additional 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } } std::cout << current_salary << std::endl; }
This code calculates an employee's new salary based on the number of completed tasks and hours worked, with a 20% increase if the tasks are over 15 and an additional 20% increase if hours worked are over 40. As you can see, the current calculations is 1200. And this can be achieved only by using nested if
statements, here some attempts to get same logic without them.
main
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 9; int hours_worked = 41; // If the number of completed tasks is greater than 15, if (completed_tasks > 15) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } // If the number of hours worked is more than 40 if (hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; } std::cout << current_salary << std::endl; }
At first it may seem that it works the same, but in this case the worker will receive an extra 20% raise, regardless of whether he has completed more than 15 tasks. Run the code and look at the output, it shows a value of 1200, even though this time the worker didn't completed more than 15 tasks.
main
#include <iostream> int main() { int current_salary = 1000; int completed_tasks = 19; int hours_worked = 39; // If the number of completed tasks is greater than 15 // AND the number of of hours worked is more than 40 if (completed_tasks > 15 && hours_worked > 40) { // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; // add an 20% increase to the current salary current_salary = current_salary + current_salary * 0.2; std::cout << current_salary << std::endl; } std::cout << current_salary << std::endl; }
У цьому випадку може здатися, що він повинен працювати як задумано, але, на жаль, це також неправильно, результат буде 1000. Це тому, що якщо працівник виконає більше 15 завдань, але не відпрацює більше 40 годин, він нічого не отримає. Отже, нам необхідно використовувати вкладені оператори if
, щоб отримати правильну реалізацію.
Note
Nested
if
statements are necessary in some cases but not always. In the third section, we'll discuss when, why and how to avoid them.
Note
Nested
if
statements are necessary in some cases but not always. In the third section, we'll discuss when, why and how to avoid them.
Swipe to show code editor
We have an excess of pink phones in our inventory that we need to sell.
- Make a 20% discount on pink phones.
- If a phone's price exceeds $1,000, the discount will be reduced to 10%.
- For all other phones, increase the price by 10%.
Рішення
solution
Дякуємо за ваш відгук!