C++ 判断语句(Conditional Statements in C++)
                           
天天向上
发布: 2025-03-28 00:06:31

原创
947 人浏览过

在 C++ 中,判断语句用于根据不同条件执行不同的代码块。常见的判断语句有 if 语句、if-else 语句、else-if 语句以及 switch 语句。


1. if 语句

if 语句用于判断条件是否为真,如果条件为真,执行相应的代码块。

语法

if (condition) {
    // 如果条件为真执行的代码
}

示例:使用 if 语句

#include <iostream>
using namespace std;

int main() {
    int a = 10;
    if (a > 5) {
        cout << "a 大于 5" << endl;
    }
    return 0;
}

输出:

a 大于 5

2. if-else 语句

if-else 语句用于在条件为真时执行一部分代码,在条件为假时执行另一部分代码。

语法

if (condition) {
    // 如果条件为真执行的代码
} else {
    // 如果条件为假执行的代码
}

示例:使用 if-else 语句

#include <iostream>
using namespace std;

int main() {
    int a = 3;
    if (a > 5) {
        cout << "a 大于 5" << endl;
    } else {
        cout << "a 小于或等于 5" << endl;
    }
    return 0;
}

输出:

a 小于或等于 5

3. if-else if-else 语句

当有多个条件需要判断时,可以使用 if-else if-else 语句。在多个条件中判断,直到遇到第一个为真的条件。

语法

if (condition1) {
    // 如果条件1为真执行的代码
} else if (condition2) {
    // 如果条件2为真执行的代码
} else {
    // 如果没有条件为真执行的代码
}

示例:使用 if-else if-else 语句

#include <iostream>
using namespace std;

int main() {
    int a = 10;
    if (a > 15) {
        cout << "a 大于 15" << endl;
    } else if (a > 5) {
        cout << "a 大于 5 但小于等于 15" << endl;
    } else {
        cout << "a 小于或等于 5" << endl;
    }
    return 0;
}

输出:

a 大于 5 但小于等于 15

4. switch 语句

switch 语句用于处理多个条件判断,适合用于基于某个变量值执行不同的代码块。switch 比多个 if-else 更高效。

语法

switch (variable) {
    case value1:
        // 当 variable == value1 时执行的代码
        break;
    case value2:
        // 当 variable == value2 时执行的代码
        break;
    // 可以有多个 case 分支
    default:
        // 如果没有任何 case 匹配时执行的代码
}

示例:使用 switch 语句

#include <iostream>
using namespace std;

int main() {
    int day = 3;
    switch (day) {
        case 1:
            cout << "星期一" << endl;
            break;
        case 2:
            cout << "星期二" << endl;
            break;
        case 3:
            cout << "星期三" << endl;
            break;
        case 4:
            cout << "星期四" << endl;
            break;
        default:
            cout << "无效的日期" << endl;
    }
    return 0;
}

输出:

星期三

5. 嵌套判断语句

if-elseswitch 语句中,我们可以使用嵌套的判断语句,即在一个判断语句中再包含其他判断语句。

示例:嵌套 if 语句

#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 5;
    if (a > 5) {
        if (b > 3) {
            cout << "a 大于 5,b 大于 3" << endl;
        }
    }
    return 0;
}

输出:

a 大于 5,b 大于 3

总结

在 C++ 中,判断语句用于根据给定的条件执行不同的代码块。常见的判断语句有:

  • if:判断条件是否为真,条件为真时执行相应的代码块。
  • if-else:条件为真时执行一个代码块,条件为假时执行另一个代码块。
  • else if:多个条件的判断,直到遇到为真的条件。
  • switch:根据变量值的不同,执行不同的代码块,适合多个固定值判断。

掌握这些判断语句的使用可以使得 C++ 程序在处理不同情况时变得灵活高效。

发表回复 0

Your email address will not be published. Required fields are marked *