温馨提示×

c++分支如何处理多条件选择

c++
小樊
86
2024-11-24 16:31:57
栏目: 编程语言

在C++中,可以使用if-else语句、switch语句或者函数指针等方法来处理多条件选择。下面是每种方法的简要说明和示例:

  1. if-else语句:
#include <iostream>
using namespace std;

int main() {
    int condition1 = 10;
    int condition2 = 20;
    int condition3 = 30;

    if (condition1 < condition2 && condition1 < condition3) {
        cout << "Condition 1 is the smallest." << endl;
    } else if (condition2 < condition1 && condition2 < condition3) {
        cout << "Condition 2 is the smallest." << endl;
    } else {
        cout << "Condition 3 is the smallest." << endl;
    }

    return 0;
}
  1. switch语句:
#include <iostream>
using namespace std;

int main() {
    int condition = 2;

    switch (condition) {
        case 1:
            cout << "Condition is 1." << endl;
            break;
        case 2:
            cout << "Condition is 2." << endl;
            break;
        case 3:
            cout << "Condition is 3." << endl;
            break;
        default:
            cout << "Invalid condition." << endl;
            break;
    }

    return 0;
}
  1. 函数指针:
#include <iostream>
using namespace std;

void condition1() {
    cout << "Condition 1 is true." << endl;
}

void condition2() {
    cout << "Condition 2 is true." << endl;
}

void condition3() {
    cout << "Condition 3 is true." << endl;
}

int main() {
    int condition = 2;
    void (*condition_func[])() = {&condition1, &condition2, &condition3};

    if (condition >= 1 && condition <= 3) {
        condition_func[condition - 1]();
    } else {
        cout << "Invalid condition." << endl;
    }

    return 0;
}

这些方法可以根据具体需求选择使用。if-else语句适用于简单的条件判断,switch语句适用于基于离散值的多个条件判断,而函数指针则适用于更复杂的条件逻辑。

0