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

การตัดสินใจ (Decision Making) ใน C++


โครงสร้างการตัดสินใจต้องการให้นักเขียนโปรแกรมระบุเงื่อนไขหนึ่งหรือหลายเงื่อนไขเพื่อให้โปรแกรมประเมินหรือทดสอบ พร้อมกับคำสั่งที่จะรันหากเงื่อนไขเป็นจริง และอาจมีคำสั่งอื่นที่จะรันหากเงื่อนไขเป็นเท็จ

นี่คือรูปแบบทั่วไปของโครงสร้างการตัดสินใจที่พบในภาษาโปรแกรมส่วนใหญ่ -

การตัดสินใจ (Decision Making) ใน C++

คำสั่ง If-Else

คำสั่ง if สามารถตามด้วยคำสั่ง else ได้ ซึ่งจะรันเมื่อนิพจน์บูลีนเป็นเท็จ ไวยากรณ์ของ if...else ใน C++ คือ -

if(boolean_expression) {
    // คำสั่งที่จะรันถ้านิพจน์บูลีนเป็นจริง
} else {
    // คำสั่งที่จะรันถ้านิพจน์บูลีนเป็นเท็จ
}

ตัวอย่างโค้ด

#include <iostream>
using namespace std;
int main() {
    // ประกาศตัวแปรท้องถิ่น:
    int a = 100;
    // ตรวจสอบเงื่อนไขบูลีน
    if( a < 20 ) {
        // ถ้าเงื่อนไขเป็นจริง พิมพ์ข้อความต่อไปนี้
        cout << "a is less than 20;" << endl;
    } else {
        // ถ้าเงื่อนไขเป็นเท็จ พิมพ์ข้อความต่อไปนี้
        cout << "a is not less than 20;" << endl;
    }
    cout << "value of a is : " << a << endl;
    return 0;
}

ผลลัพธ์

a is not less than 20;
value of a is : 100

คำสั่ง Switch-Case

คำสั่ง switch อนุญาตให้ทดสอบตัวแปรเทียบเท่ากับรายการค่า แต่ละค่าเรียกว่า case และตัวแปรที่ถูก switch จะถูกตรวจสอบกับแต่ละ case ไวยากรณ์สำหรับคำสั่ง switch ใน C++ คือดังนี้ -

switch(expression) {
    case constant-expression :
        statement(s);
        break; //optional
    case constant-expression :
        statement(s);
        break; //optional
    // คุณสามารถมี case statement ได้ไม่จำกัดจำนวน
    default : //Optional
        statement(s);
}

ตัวอย่างโค้ด

#include <iostream>
using namespace std;
int main() {
    // ประกาศตัวแปรท้องถิ่น:
    char grade = 'D';
    switch(grade) {
        case 'A' :
            cout << "Excellent!" << endl;
            break;
        case 'B' :
        case 'C' :
            cout << "Well done" << endl;
            break;
        case 'D' :
            cout << "You passed" << endl;
            break;
        case 'F' :
            cout << "Better try again" << endl;
            break;
        default :
            cout << "Invalid grade" << endl;
    }
    cout << "Your grade is " << grade << endl;
    return 0;
}

ผลลัพธ์

You passed
Your grade is D