Featured image of post 04x程序流程结构

04x程序流程结构

关注公众号,后台回复 找书+ C++Primer 获取C++相关电子书。

选择结构

判断语句

C++ 编程语言提供了以下类型的判断语句。点击链接查看每个语句的细节。

语句描述
if 语句一个 if 语句 由一个布尔表达式后跟一个或多个语句组成。
if…else 语句一个 if 语句 后可跟一个可选的 else 语句,else 语句在布尔表达式为假时执行。
嵌套 if 语句您可以在一个 if 或 else if 语句内使用另一个 if 或 else if 语句。
switch 语句一个 switch 语句允许测试一个变量等于多个值时的情况。
嵌套 switch 语句您可以在一个 switch 语句内使用另一个 switch 语句。
 1#include<iostream>  
 2using namespace std;
 3
 4int main() {
 5    int x, y, z;
 6
 7    // 让用户输入 x, y, z 的值
 8    cout << "请输入 x 的值: ";
 9    cin >> x;
10    cout << "请输入 y 的值: ";
11    cin >> y;
12    cout << "请输入 z 的值: ";
13    cin >> z;
14
15    // 单行 if
16    if (x < y) cout << "x 小于 y" << endl;
17
18    // 多行 if
19    if (x < y) {
20        cout << "x 小于 y" << endl;
21        cout << "这是一个多行 if 语句" << endl;
22    }
23
24    // 嵌套 if
25    if (x < y) {
26        if (y < z) {
27            cout << "y 小于 z" << endl;
28        }
29        else {
30            cout << "y 不小于 z" << endl;
31        }
32    }
33    else {
34        cout << "x 不小于 y" << endl;
35    }
36
37    cin.get(); // 使程序暂停,等待用户输入
38    return 0;
39}

image-20250120100241518

? : 运算符(三目表达式同C)

我们已经在前面的章节中讲解了 条件运算符 ? :,可以用来替代 if…else 语句。它的一般形式如下:

Exp1 ? Exp2 : Exp3;

其中,Exp1、Exp2 和 Exp3 是表达式。请注意,冒号的使用和位置。

? 表达式的值是由 Exp1 决定的。如果 Exp1 为真,则计算 Exp2 的值,结果即为整个 ? 表达式的值。如果 Exp1 为假,则计算 Exp3 的值,结果即为整个 ? 表达式的值。

 1#include<iostream>  
 2using namespace std;
 3
 4int main() {
 5    int x, y, z;
 6
 7    // 让用户输入 x, y, z 的值
 8    cout << "请输入 x 的值: ";
 9    cin >> x;
10    cout << "请输入 y 的值: ";
11    cin >> y;
12    cout << "请输入 z 的值: ";
13    cin >> z;
14
15    // 使用三目运算符改写嵌套 if
16    cout << (x < y ? (y < z ? "y 小于 z" : "y 不小于 z") : "x 不小于 y") << endl;
17
18
19    cin.get(); // 使程序暂停,等待用户输入
20    return 0;
21}

image-20250120100511647

Switch结构

 1#include<iostream>  
 2using namespace std;
 3
 4int main() {
 5    int score;
 6
 7    while (true) {
 8        // 让用户输入分数
 9        cout << "请输入分数(输入-1退出): ";
10        cin >> score;
11
12        // 检查是否输入-1以退出循环
13        if (score == -1) {
14            break;
15        }
16
17        // 使用 switch 和嵌套 switch 判断分数等级
18        switch (score / 10) {
19        case 10:
20        case 9:
21            switch (score) {
22            case 100:
23            case 99:
24                cout << "A++" << endl;
25                break;
26            case 98:
27            case 97:
28            case 96:
29            case 95:
30                cout << "A+" << endl;
31                break;
32            default:
33                cout << "A" << endl;
34                break;
35            }
36            break;
37        case 8:
38            cout << "B" << endl;
39            break;
40        case 7:
41            cout << "C" << endl;
42            break;
43        case 6:
44            cout << "D" << endl;
45            break;
46        default:
47            cout << "E" << endl;
48            break;
49        }
50    }
51
52    return 0;
53}

image-20250120114048360

循环结构

循环类型

C++ 编程语言提供了以下几种循环类型。点击链接查看每个类型的细节。

循环类型描述
while 循环当给定条件为真时,重复语句或语句组。它会在执行循环主体之前测试条件。
for 循环多次执行一个语句序列,简化管理循环变量的代码。
do…while 循环除了它是在循环主体结尾测试条件外,其他与 while 语句类似。
嵌套循环您可以在 while、for 或 do..while 循环内使用一个或多个循环。
 1while(condition)
 2{
 3   statement(s);
 4}
 5
 6for ( init; condition; increment )  // 均为空表示无限真值循环
 7{
 8   statement(s);
 9}
10
11
12do
13{
14   statement(s);
15
16}while( condition );
 1#include<iostream>  
 2using namespace std;
 3
 4int main() {
 5    int i;
 6
 7    // do-while 循环
 8    i = 1;
 9    cout << "do-while 循环:" << endl;
10    do {
11        cout << i << " ";
12        i++;
13    } while (i <= 5);
14    cout << endl;
15
16    // while 循环
17    i = 1;
18    cout << "while 循环:" << endl;
19    while (i <= 5) {
20        cout << i << " ";
21        i++;
22    }
23    cout << endl;
24
25    // for 循环
26    cout << "for 循环:" << endl;
27    for (i = 1; i <= 5; i++) {
28        cout << i << " ";
29    }
30    cout << endl;
31
32    return 0;
33}

image-20250120115404114

嵌套循环

 1#include <iostream>
 2using namespace std;
 3
 4int main() {
 5    cout << "99 乘法表:" << endl;
 6
 7    for (int i = 1; i <= 9; i++) {
 8        for (int j = 1; j <= i; j++) {
 9            cout << j << " * " << i << " = " << j * i << "\t";
10        }
11        cout << endl;
12    }
13
14    return 0;
15}

image-20250120161945774

跳转语句-循环控制语句

循环控制语句更改执行的正常序列。当执行离开一个范围时,所有在该范围中创建的自动对象都会被销毁。

C++ 提供了下列的控制语句。点击链接查看每个语句的细节。

控制语句描述
break 语句终止 loop 或 switch 语句,程序流将继续执行紧接着 loop 或 switch 的下一条语句。
continue 语句引起循环跳过主体的剩余部分,立即重新开始测试条件。
goto 语句将控制转移到被标记的语句。但是不建议在程序中使用 goto 语句。
 1#include <iostream>
 2using namespace std;
 3
 4int main() {
 5    cout << "示例程序展示 break, continue 和 goto 的用法:" << endl;
 6
 7    for (int i = 1; i <= 20; i++) {
 8        if (i == 5) {
 9            cout << "遇到 5,使用 continue 跳过本次循环" << endl;
10            continue; // 跳过本次循环,继续下一次循环
11        }
12
13        if (i == 10) {
14            cout << "遇到 10,使用 break 退出当前循环" << endl;
15            break; // 退出当前循环
16        }
17
18        cout << "当前数字: " << i << endl;
19    }
20
21    // 使用 goto 跳转到标签 start2
22    cout << "使用 goto 跳转到标签 start2" << endl;
23    goto start2;  //慎用goto,容易死循环。
24
25start2:
26    for (int j = 11; j <= 20; j++) {
27        if (j == 15) {
28            cout << "遇到 15,使用 goto 跳转到标签 end" << endl;
29            goto end; // 跳转到标签 end
30        }
31
32        cout << "当前数字: " << j << endl;
33    }
34
35end:
36    cout << "程序结束" << endl;
37    return 0;
38}

image-20250120163428616

经典案例

经典案例-猜数字游戏

 1#include <iostream>
 2#include <cstdlib> // 包含 rand() 和 srand()
 3#include <ctime>   // 包含 time()
 4using namespace std;
 5
 6int main() {
 7    srand(static_cast<unsigned int>(time(0))); // 使用当前时间作为随机数种子
 8    int numberToGuess = rand() % 100 + 1; // 生成 1 到 100 之间的随机数
 9    int guess;
10    int attempts = 0;
11    char playAgain;
12
13    do {
14        cout << "猜数字游戏开始!" << endl;
15        cout << "我已经想好了一个 1 到 100 之间的数字。" << endl;
16
17        // while 循环用于猜测数字
18        while (true) {
19            cout << "请输入你的猜测: ";
20            cin >> guess;
21            attempts++;
22
23            if (guess < numberToGuess) {
24                cout << "太小了!" << endl;
25            }
26            else if (guess > numberToGuess) {
27                cout << "太大了!" << endl;
28            }
29            else {
30                cout << "恭喜你,猜对了!你用了 " << attempts << " 次猜对了数字。" << endl;
31                break;
32            }
33        }
34
35        // for 循环用于询问是否再次玩游戏
36        for (;;) {
37            cout << "你想再玩一次吗?(y/n): ";
38            cin >> playAgain;
39            if (playAgain == 'y' || playAgain == 'Y' || playAgain == 'n' || playAgain == 'N') {
40                break;
41            }
42            else {
43                cout << "无效输入,请输入 'y' 或 'n'。" << endl;
44            }
45        }
46
47        if (playAgain == 'y' || playAgain == 'Y') {
48            numberToGuess = rand() % 100 + 1; // 生成新的随机数
49            attempts = 0; // 重置尝试次数
50        }
51
52    } while (playAgain == 'y' || playAgain == 'Y');
53
54    cout << "感谢你玩猜数字游戏!" << endl;
55    return 0;
56}

image-20250120120245397

经典案例-水仙花数

 1#include <iostream>
 2#include <cmath> // 包含 pow() 函数
 3using namespace std;
 4/*
 5* 次方之和等于该数本身。例如,对于三位数来说,如果一个数等于其各位数字的立方和,则该数为水仙花数。
 6例如:
 7•	153 是一个三位数的水仙花数,因为 (1^3 + 5^3 + 3^3 = 153)。
 8•	370 是一个三位数的水仙花数,因为 (3^3 + 7^3 + 0^3 = 370)。
 9*/
10int main() {
11    int number = 100; // 从 100 开始,因为 100 是最小的三位数
12
13    cout << "三位数中的所有水仙花数如下:" << endl;
14
15    do {
16        int sum = 0;
17		int temp = number; // 临时变量,用于计算各位数字的立方和
18        while (temp > 0) {
19            int digit = temp % 10;
20            sum += pow(digit, 3);
21            temp /= 10;  // temp=temp/10,每次循环往前近一位,去掉最后一位
22        }
23
24        if (sum == number) {
25            cout << number << " ";
26        }
27
28        number++;
29    } while (number <= 999); // 999 是最大的三位数
30
31    cout << endl;
32    return 0;
33}

image-20250120120810863

拓展:四位水仙花数

image-20250120144932477

经典案例-敲桌子游戏

 1#include <iostream>
 2#include <string> // 添加此行以包含字符串库
 3using namespace std;
 4
 5int main() {
 6    cout << "敲桌子游戏开始!" << endl;
 7
 8    for (int i = 1; i <= 100; i++) {
 9        // 检查是否是 7 的倍数或者包含数字 7
10        if (i % 7 == 0 || to_string(i).find('7') != string::npos) {
11            cout << "敲桌子" << endl;
12        }
13        else {
14            cout << i << endl;
15        }
16    }
17
18    return 0;
19}

image-20250120161234972


🔔 想要获取更多网络安全与编程技术干货?

关注 泷羽Sec-静安 公众号,与你一起探索前沿技术,分享实用的学习资源与工具。我们专注于深入分析,拒绝浮躁,只做最实用的技术分享!💻

扫描下方二维码,马上加入我们,共同成长!🌟

👉 长按或扫描二维码关注公众号

或者直接回复文章中的关键词,获取更多技术资料与书单推荐!📚

Licensed under CC BY-NC-SA 4.0