从零开始学习C++(七.C++流程控制)

183 阅读1分钟

「这是我参与2022首次更文挑战的第7天,活动详情查看:2022首次更文挑战

前言

条件控制是最常见的代码了,主要分类两个类型,判断和循环,下面弄点代码实际试试。

判断

if判断

写一个简单判断奇数偶数的代码:

#include <iostream>
using namespace std;

int main()
{
	int num;
	cout << "输入一个数:";
	cin >> num;
	if (num % 2 == 0) {
		cout<<"是个偶数"<<endl;
	}else{
		cout<<"是个奇数"<<endl;
	}
}

cin 就是收集用户的输入,cout就是向屏幕输出,endl就是结束当行输出的IO操作。

switch 判断

#include <iostream>
using namespace std;

int main()
{
    int grade;
    cout << "输入一个5以内的数字:";
    cin >> grade;

    switch (grade)
    {
    case 1:
        cout << "丑" << endl;
        break;
    case 2:
        cout << "不丑" << endl;
        break;
    case 3:
        cout << "不好看" << endl;
        break;
    case 4:
        cout << "还行" << endl;
        break;
    case 5:
        cout << "好看" << endl;
        break;
    default:
        cout << "太好看了吧" << endl;
    }
    return 0;
}

switch要使用break才能跳出循环,不然会执行每一个case,而if els不是这样,相对来说switch的效率更高,swith不能有表达式,可以做范围判断,只是进行跳转,if else是逻辑判断。

循环

while循环

while里面只有判断,判断不成立就执行下面的语句

#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    cout << "倒数十个数:" << endl;
    while (a > 0)
    {
        cout << a << endl;
        a--;
     
    }
    cout << "结束" << endl;
    return 0;
}

image.png

for循环

for里面有初始化,判断,增连运算符,使代码更简洁。

#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    cout << "倒数十个数:" << endl;
    for (a;a > 0;a--)
    {
        cout << a << endl;
    }
    cout << "结束" << endl;
    return 0;
}

image.png

do while

反过来的while循环,在其他语言中比较少用,或者说几乎不用。

#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    cout << "倒数十个数:" << endl;
    do
    {
        cout << a << endl;
        a--;
    } while (a > 0);
    cout << "结束" << endl;
    return 0;
}

image.png

其他

还有一些基本的流程控制关键字,例如continuegotolabel,continue就是跳出当前循环语句,执行循环语句的下面的语句,goto跳转现在几乎也看不到了,几乎所有的语言都不推荐使用这个,这个会使代码流程非常混乱,极易出错。

总结

今天写了很多小块的代码,写代码还是很有作用的,不然只记了一个大概印象,过一段时间就忘记了,在实际的代码编写中会出现很多问题,这些问题不断地在提醒自己需要更仔细同时也加深了自己对某个小知识的印象,后面继续多写写,不管多简单,能运行就是好代码。