Skip to content

流程控制

流程控制语句用于控制程序的执行顺序。C++提供了条件语句和循环语句来控制程序流程。本章将详细介绍C++的流程控制语句。

条件语句

if语句

cpp
#include <iostream>
using namespace std;

int main() {
    // ============ 基本if语句 ============
    
    int score = 75;
    
    // 单分支if语句
    if (score >= 60) {
        cout << "恭喜,你及格了!" << endl;
    }
    
    // if-else双分支语句
    if (score >= 60) {
        cout << "及格" << endl;
    } else {
        cout << "不及格" << endl;
    }
    
    // if-else if-else多分支语句
    if (score >= 90) {
        cout << "优秀" << endl;
    } else if (score >= 80) {
        cout << "良好" << endl;
    } else if (score >= 60) {
        cout << "及格" << endl;
    } else {
        cout << "不及格" << endl;
    }
    
    
    // ============ if语句嵌套 ============
    
    int age = 25;
    bool hasLicense = true;
    
    // 嵌套if语句
    if (age >= 18) {
        cout << "\n年龄符合要求" << endl;
        if (hasLicense) {
            cout << "有驾照,可以驾驶" << endl;
        } else {
            cout << "没有驾照,不能驾驶" << endl;
        }
    } else {
        cout << "年龄不符合要求" << endl;
    }
    
    // 使用逻辑运算符简化
    if (age >= 18 && hasLicense) {
        cout << "可以驾驶" << endl;
    }
    
    
    // ============ if语句注意事项 ============
    
    int x = 10;
    
    // 悬空else问题
    if (x > 0)
        if (x > 5)
            cout << "\nx > 5" << endl;
        else  // 这个else与最近的if匹配
            cout << "0 < x <= 5" << endl;
    
    // 使用大括号明确结构
    if (x > 0) {
        if (x > 5) {
            cout << "x > 5" << endl;
        } else {
            cout << "0 < x <= 5" << endl;
        }
    }
    
    
    // ============ if初始化语句(C++17) ============
    
    // 在if条件中声明变量
    // if (int val = getValue(); val > 0) {
    //     cout << "val = " << val << endl;
    // }
    // val在这里不可见
    
    return 0;
}

switch语句

cpp
#include <iostream>
using namespace std;

int main() {
    // ============ 基本switch语句 ============
    
    int day = 3;
    
    cout << "星期" << day << "是:";
    
    switch (day) {
        case 1:
            cout << "星期一" << endl;
            break;  // 跳出switch
        case 2:
            cout << "星期二" << endl;
            break;
        case 3:
            cout << "星期三" << endl;
            break;
        case 4:
            cout << "星期四" << endl;
            break;
        case 5:
            cout << "星期五" << endl;
            break;
        case 6:
            cout << "星期六" << endl;
            break;
        case 7:
            cout << "星期日" << endl;
            break;
        default:  // 默认情况
            cout << "无效的日期" << endl;
    }
    
    
    // ============ switch穿透 ============
    
    char grade = 'B';
    
    cout << "\n成绩等级 " << grade << ":";
    
    switch (grade) {
        case 'A':
        case 'a':  // A和a执行相同的代码
            cout << "优秀" << endl;
            break;
        case 'B':
        case 'b':
            cout << "良好" << endl;
            break;
        case 'C':
        case 'c':
            cout << "及格" << endl;
            break;
        case 'D':
        case 'd':
            cout << "不及格" << endl;
            break;
        default:
            cout << "无效的等级" << endl;
    }
    
    
    // ============ switch表达式(C++17) ============
    
    // 使用switch作为表达式
    // int result = switch (day) {
    //     case 1: case 7: return 0;  // 周末
    //     default: return 1;         // 工作日
    // };
    
    
    // ============ switch与枚举 ============
    
    enum Color { RED, GREEN, BLUE };
    Color color = GREEN;
    
    cout << "\n颜色:";
    
    switch (color) {
        case RED:
            cout << "红色" << endl;
            break;
        case GREEN:
            cout << "绿色" << endl;
            break;
        case BLUE:
            cout << "蓝色" << endl;
            break;
    }
    
    
    // ============ switch注意事项 ============
    
    // switch只能用于整型、字符型和枚举类型
    // double d = 3.14;
    // switch (d) { }  // 错误!不能用于浮点类型
    
    // case标签必须是常量表达式
    // int x = 1;
    // switch (day) {
    //     case x:  // 错误!x不是常量
    // }
    
    return 0;
}

循环语句

while循环

cpp
#include <iostream>
using namespace std;

int main() {
    // ============ 基本while循环 ============
    
    // 打印1到5
    int i = 1;
    while (i <= 5) {
        cout << i << " ";
        i++;  // 更新循环变量
    }
    cout << endl;
    
    
    // ============ 计算累加和 ============
    
    int sum = 0;
    int n = 100;
    i = 1;
    
    while (i <= n) {
        sum += i;
        i++;
    }
    
    cout << "1到" << n << "的和 = " << sum << endl;
    
    
    // ============ 输入验证 ============
    
    int number;
    
    cout << "\n请输入一个正整数: ";
    cin >> number;
    
    // 确保输入是正整数
    while (number <= 0) {
        cout << "输入无效,请重新输入正整数: ";
        cin >> number;
    }
    
    cout << "你输入的正整数是: " << number << endl;
    
    
    // ============ 猜数字游戏 ============
    
    int secret = 42;  // 秘密数字
    int guess;
    
    cout << "\n猜数字游戏(1-100)" << endl;
    
    // while (true) {
    //     cout << "请输入你的猜测: ";
    //     cin >> guess;
        
    //     if (guess == secret) {
    //         cout << "恭喜你猜对了!" << endl;
    //         break;  // 跳出循环
    //     } else if (guess < secret) {
    //         cout << "太小了,再试试!" << endl;
    //     } else {
    //         cout << "太大了,再试试!" << endl;
    //     }
    // }
    
    
    // ============ while循环注意事项 ============
    
    // 死循环(缺少更新条件)
    // while (true) {
    //     // 无限循环
    // }
    
    // 空循环体
    i = 0;
    while (i++ < 10);  // 空循环体,只执行i++
    cout << "\ni = " << i << endl;
    
    return 0;
}

do-while循环

cpp
#include <iostream>
using namespace std;

int main() {
    // ============ 基本do-while循环 ============
    
    // do-while至少执行一次
    int i = 1;
    
    do {
        cout << i << " ";
        i++;
    } while (i <= 5);
    cout << endl;
    
    
    // ============ 与while的区别 ============
    
    // while可能一次都不执行
    i = 10;
    while (i < 5) {
        cout << "while: " << i << endl;  // 不执行
        i++;
    }
    
    // do-while至少执行一次
    i = 10;
    do {
        cout << "do-while: " << i << endl;  // 执行一次
        i++;
    } while (i < 5);
    
    
    // ============ 菜单选择 ============
    
    int choice;
    
    cout << "\n===== 简单计算器 =====" << endl;
    
    do {
        cout << "\n1. 加法" << endl;
        cout << "2. 减法" << endl;
        cout << "3. 乘法" << endl;
        cout << "4. 除法" << endl;
        cout << "0. 退出" << endl;
        cout << "请选择: ";
        cin >> choice;
        
        double a, b;
        
        switch (choice) {
            case 1:
                cout << "输入两个数: ";
                cin >> a >> b;
                cout << a << " + " << b << " = " << a + b << endl;
                break;
            case 2:
                cout << "输入两个数: ";
                cin >> a >> b;
                cout << a << " - " << b << " = " << a - b << endl;
                break;
            case 3:
                cout << "输入两个数: ";
                cin >> a >> b;
                cout << a << " * " << b << " = " << a * b << endl;
                break;
            case 4:
                cout << "输入两个数: ";
                cin >> a >> b;
                if (b != 0) {
                    cout << a << " / " << b << " = " << a / b << endl;
                } else {
                    cout << "除数不能为0" << endl;
                }
                break;
            case 0:
                cout << "感谢使用!" << endl;
                break;
            default:
                cout << "无效选择,请重试" << endl;
        }
    } while (choice != 0);
    
    return 0;
}

for循环

cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
    // ============ 基本for循环 ============
    
    // 打印1到5
    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    cout << endl;
    
    
    // ============ for循环的各个部分 ============
    
    // for (初始化; 条件; 更新) { 循环体 }
    
    // 初始化只执行一次
    // 条件在每次循环前检查
    // 更新在每次循环后执行
    
    int sum = 0;
    
    // 计算1到100的和
    for (int i = 1; i <= 100; i++) {
        sum += i;
    }
    
    cout << "1到100的和 = " << sum << endl;
    
    
    // ============ for循环变体 ============
    
    // 省略初始化
    int j = 0;
    for (; j < 5; j++) {
        cout << j << " ";
    }
    cout << endl;
    
    // 省略条件(无限循环)
    // for (int i = 0; ; i++) {
    //     if (i >= 5) break;
    //     cout << i << " ";
    // }
    
    // 省略更新
    for (int i = 0; i < 5; ) {
        cout << i << " ";
        i++;  // 在循环体内更新
    }
    cout << endl;
    
    // 全部省略(无限循环)
    // for (;;) {
    //     // 无限循环
    // }
    
    
    // ============ 多变量for循环 ============
    
    // 同时初始化和更新多个变量
    for (int i = 0, j = 10; i < j; i++, j--) {
        cout << "i=" << i << ", j=" << j << endl;
    }
    
    
    // ============ 嵌套for循环 ============
    
    // 打印乘法表
    cout << "\n九九乘法表:" << endl;
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << "*" << i << "=" << i * j << "\t";
        }
        cout << endl;
    }
    
    
    // ============ 范围for循环(C++11) ============
    
    vector<int> numbers = {1, 2, 3, 4, 5};
    
    cout << "\n范围for循环:" << endl;
    
    // 只读访问
    for (int n : numbers) {
        cout << n << " ";
    }
    cout << endl;
    
    // 使用auto自动推导类型
    for (auto n : numbers) {
        cout << n << " ";
    }
    cout << endl;
    
    // 修改元素(使用引用)
    for (int& n : numbers) {
        n *= 2;  // 每个元素乘以2
    }
    
    // 输出修改后的值
    for (const int& n : numbers) {
        cout << n << " ";
    }
    cout << endl;
    
    // 遍历数组
    int arr[] = {10, 20, 30, 40, 50};
    for (int n : arr) {
        cout << n << " ";
    }
    cout << endl;
    
    // 遍历字符串
    string str = "Hello";
    for (char c : str) {
        cout << c << " ";
    }
    cout << endl;
    
    return 0;
}

跳转语句

break语句

cpp
#include <iostream>
using namespace std;

int main() {
    // ============ break在循环中 ============
    
    // 找到第一个能被7整除的数
    for (int i = 1; i <= 100; i++) {
        if (i % 7 == 0) {
            cout << "第一个能被7整除的数是: " << i << endl;
            break;  // 跳出循环
        }
    }
    
    
    // ============ break在嵌套循环中 ============
    
    // break只跳出当前所在的循环
    bool found = false;
    
    for (int i = 1; i <= 10 && !found; i++) {
        for (int j = 1; j <= 10; j++) {
            if (i * j == 56) {
                cout << "\n找到: " << i << " * " << j << " = 56" << endl;
                found = true;
                break;  // 只跳出内层循环
            }
        }
    }
    
    // 使用标志变量跳出外层循环
    // 或使用goto语句(不推荐)
    
    
    // ============ break在switch中 ============
    
    char grade = 'B';
    
    cout << "\n成绩等级: ";
    switch (grade) {
        case 'A':
            cout << "优秀" << endl;
            break;
        case 'B':
            cout << "良好" << endl;
            break;  // 跳出switch
        case 'C':
            cout << "及格" << endl;
            break;
    }
    
    
    // ============ 实际应用 ============
    
    // 查找元素
    int arr[] = {3, 7, 2, 9, 5};
    int target = 9;
    int index = -1;
    
    for (int i = 0; i < 5; i++) {
        if (arr[i] == target) {
            index = i;
            break;  // 找到后立即退出
        }
    }
    
    if (index != -1) {
        cout << "\n找到 " << target << " 在位置 " << index << endl;
    } else {
        cout << "\n未找到 " << target << endl;
    }
    
    return 0;
}

continue语句

cpp
#include <iostream>
using namespace std;

int main() {
    // ============ continue在循环中 ============
    
    // 打印1到10中的奇数
    cout << "1到10中的奇数: ";
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // 跳过偶数,进入下一次迭代
        }
        cout << i << " ";
    }
    cout << endl;
    
    
    // ============ 跳过特定条件 ============
    
    // 打印1到20中不能被3整除的数
    cout << "\n1到20中不能被3整除的数: ";
    for (int i = 1; i <= 20; i++) {
        if (i % 3 == 0) {
            continue;  // 跳过能被3整除的数
        }
        cout << i << " ";
    }
    cout << endl;
    
    
    // ============ 处理数据 ============
    
    // 只处理有效数据
    int scores[] = {85, -1, 92, 78, -1, 95, 88};
    int count = 0;
    int sum = 0;
    
    cout << "\n有效分数: ";
    for (int score : scores) {
        if (score < 0) {
            continue;  // 跳过无效分数
        }
        cout << score << " ";
        sum += score;
        count++;
    }
    cout << endl;
    
    if (count > 0) {
        cout << "平均分: " << (double)sum / count << endl;
    }
    
    
    // ============ continue与while ============
    
    // 注意:在while中使用continue时要确保更新循环变量
    int i = 0;
    cout << "\nwhile中的continue: ";
    while (i < 10) {
        i++;
        if (i % 2 == 0) {
            continue;  // 跳过偶数
        }
        cout << i << " ";
    }
    cout << endl;
    
    return 0;
}

goto语句

cpp
#include <iostream>
using namespace std;

int main() {
    // ============ goto语句 ============
    
    // goto语句可以无条件跳转到标签
    // 不推荐使用,会破坏程序结构
    
    cout << "程序开始" << endl;
    
    goto skip;  // 跳转到skip标签
    
    cout << "这行不会执行" << endl;
    
skip:
    cout << "跳到这里" << endl;
    
    
    // ============ goto的实际用途 ============
    
    // 1. 跳出多层嵌套循环
    int arr[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    int target = 5;
    bool found = false;
    int row = -1, col = -1;
    
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (arr[i][j] == target) {
                found = true;
                row = i;
                col = j;
                goto found_target;  // 直接跳出多层循环
            }
        }
    }
    
    // 如果没找到
    cout << "\n未找到目标" << endl;
    goto end_search;
    
found_target:
    cout << "\n找到 " << target << " 在位置 [" << row << "][" << col << "]" << endl;
    
end_search:
    // 继续执行其他代码
    cout << "搜索结束" << endl;
    
    
    // ============ goto的替代方案 ============
    
    // 推荐:使用函数和返回值代替goto
    // 或者使用标志变量
    
    // 使用标志变量
    found = false;
    for (int i = 0; i < 3 && !found; i++) {
        for (int j = 0; j < 3; j++) {
            if (arr[i][j] == target) {
                found = true;
                row = i;
                col = j;
                break;
            }
        }
    }
    
    if (found) {
        cout << "\n使用标志变量找到目标" << endl;
    }
    
    
    // ============ goto注意事项 ============
    
    /*
     * goto的使用建议:
     * 
     * 1. 避免使用goto,它会破坏程序结构
     * 2. 不要跳过变量初始化
     * 3. 不要跳入循环或代码块内部
     * 4. 只在极少数情况下使用(如错误处理、跳出多层循环)
     * 5. 优先使用break、continue、return、异常处理
     */
    
    return 0;
}

return语句

cpp
#include <iostream>
using namespace std;

// 返回值的函数
int add(int a, int b) {
    return a + b;  // 返回计算结果
}

// 无返回值的函数
void printMessage(string msg) {
    cout << msg << endl;
    return;  // 可选,void函数可以省略return
}

// 提前返回
bool isPrime(int n) {
    if (n <= 1) {
        return false;  // 提前返回
    }
    
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;  // 发现因子,不是素数
        }
    }
    
    return true;  // 是素数
}

// 查找元素,返回索引
int findElement(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i;  // 找到,返回索引
        }
    }
    return -1;  // 未找到,返回-1
}

int main() {
    // ============ return在函数中 ============
    
    int result = add(10, 20);
    cout << "add(10, 20) = " << result << endl;
    
    printMessage("Hello, C++!");
    
    
    // ============ return提前退出 ============
    
    cout << "\n素数检查:" << endl;
    
    for (int i = 1; i <= 20; i++) {
        if (isPrime(i)) {
            cout << i << " 是素数" << endl;
        }
    }
    
    
    // ============ return在main中 ============
    
    int arr[] = {3, 7, 2, 9, 5};
    int index = findElement(arr, 5, 9);
    
    if (index != -1) {
        cout << "\n找到元素在索引 " << index << endl;
    } else {
        cout << "\n未找到元素" << endl;
    }
    
    // main函数的返回值表示程序状态
    // return 0;  // 正常退出
    // return 1;  // 异常退出
    
    return 0;
}

循环应用实例

cpp
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    // ============ 计算阶乘 ============
    
    int n = 10;
    long long factorial = 1;
    
    for (int i = 1; i <= n; i++) {
        factorial *= i;
    }
    
    cout << n << "! = " << factorial << endl;
    
    
    // ============ 斐波那契数列 ============
    
    cout << "\n斐波那契数列前20项:" << endl;
    
    long long fib1 = 0, fib2 = 1;
    
    for (int i = 0; i < 20; i++) {
        cout << fib1 << " ";
        
        long long next = fib1 + fib2;
        fib1 = fib2;
        fib2 = next;
    }
    cout << endl;
    
    
    // ============ 判断素数 ============
    
    int num = 97;
    bool isPrime = true;
    
    if (num <= 1) {
        isPrime = false;
    } else {
        for (int i = 2; i <= sqrt(num); i++) {
            if (num % i == 0) {
                isPrime = false;
                break;
            }
        }
    }
    
    cout << "\n" << num << (isPrime ? " 是" : " 不是") << "素数" << endl;
    
    
    // ============ 水仙花数 ============
    
    cout << "\n水仙花数(三位数):" << endl;
    
    for (int i = 100; i < 1000; i++) {
        int hundreds = i / 100;
        int tens = (i / 10) % 10;
        int ones = i % 10;
        
        if (hundreds * hundreds * hundreds + 
            tens * tens * tens + 
            ones * ones * ones == i) {
            cout << i << " ";
        }
    }
    cout << endl;
    
    
    // ============ 打印图案 ============
    
    cout << "\n金字塔图案:" << endl;
    
    int rows = 5;
    for (int i = 1; i <= rows; i++) {
        // 打印空格
        for (int j = 1; j <= rows - i; j++) {
            cout << " ";
        }
        // 打印星号
        for (int j = 1; j <= 2 * i - 1; j++) {
            cout << "*";
        }
        cout << endl;
    }
    
    
    // ============ 二分查找 ============
    
    int sortedArr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
    int size = 10;
    int target = 13;
    
    int left = 0, right = size - 1;
    int foundIndex = -1;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        
        if (sortedArr[mid] == target) {
            foundIndex = mid;
            break;
        } else if (sortedArr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    cout << "\n二分查找 " << target << ": ";
    if (foundIndex != -1) {
        cout << "找到,索引 = " << foundIndex << endl;
    } else {
        cout << "未找到" << endl;
    }
    
    return 0;
}

本章小结

本章学习了:

  • 条件语句:if、if-else、if-else if-else、switch
  • 循环语句:while、do-while、for、范围for
  • 跳转语句:break、continue、goto、return
  • 循环应用:阶乘、斐波那契数列、素数判断、二分查找

下一章,我们将学习函数,了解C++函数的定义和使用。