Javer 学 c++(五):流程结构篇

105 阅读2分钟

总览

主要讲了 c++ 中三种程序流程结构:

一、顺序结构:程序按顺序发生,不发生跳转

二、选择结构:依据条件是否满足,有选择的执行相应功能

三、循环结构:依据条件是否满足,循环多次执行某段代码

选择结构

if 类型

和 Java 完全一致,仅给出代码

#include <iostream>
using namespace std;

int main() {
    // 如果得分超过 90,说明为优秀,否则为差
    int score = 0;

    cin >> score;
    // 单行 if
    if (score > 90) {
        cout << "Your score is good" << endl;
    }
    // 多行 if
    if (score > 90) {
        cout << "Your score is good" << endl;
    } else {
        cout << "Your score is bad" << endl;
    }
    // 多条件 if
    if (score > 90) {
        cout << "Your score is between 90 - 100" << endl;
    } else if (score > 60) {
        cout << "Your score is between 60 - 90" << endl;
    } else {
        cout << "Your score is between 0 - 60" << endl;
    }

    return 0;
}

三目运算符

#include <iostream>
using namespace std;

int main() {

    int a = 100;
    int b = 200;

    cout << (a > b ? a : b) << endl;

    return 0;
}

和 Java 完全相同

switch 语句

作用:执行多条件语句

#include <iostream>
using namespace std;

int main() {
    
    int score = 0;
    cin >> score;

    switch (score) {
        case 1:
            cout << 1 << endl;
        case 2:
            cout << 2 << endl;
        default:
            cout << "other" << endl;
    }
    
    return 0;
}

类 Java

循环语句

while 语句

#include <iostream>
using namespace std;

int main() {

    int num = 1;

    while (num <= 10) {
        cout << num << endl;
        num++;
    }

    return 0;
}

do while 语句

语法:do {循环语句} while {循环条件}

区别:因为先先执行后判断,所以必定会执行一次

#include <iostream>
using namespace std;

int main() {

    int num = 1;

    do {
        cout << num << endl;
        num++;
    }
    while (num <= 10);

    return 0;
}

for 循环

#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 10; i++) {
        cout << i << endl;
    }

    return 0;
}

类 Java,用法和格式基本一致

跳转语句

break

作用:用于跳出选择结构 or 循环结构

使用时机:

  • 在 switch 中时,用于终止 case 并跳出 switch
  • 用于循环语句中时,用于跳出循环语句
  • 出现在嵌套循环时,用于跳出最近的内层循环

continue

用于跳过本次循环中尚未执行的代码

以上两个都和 Java 中类似

goto

作用:可以无条件跳转语句

语法:goto 标记 解释:如果标记的名称存在,执行到 goto 语句时,会跳转到标记的位置

和 Java 比较: goto 允许在代码任意位置跳转,容易形成交错的跳转网,Java 出于可维护性考虑,没有使用 goto 关键字

重点:不推荐使用哈哈哈哈哈

#include <iostream>
using namespace std;

int main() {

    cout << 1 << endl;

    goto flag;

    cout << 2 << endl;

    flag:
    cout << 3 << endl;
    
    return 0;
}