switch语句就是根据输入条件判断该走{}中的哪个分支;

#include <iostream>
using namespace std;
int main()
{
    int grade;
    cout << "请输入学生成绩" << endl;
    cin >> grade;
    switch(grade)//易找 grade 的大小 判断从第几行开始执行,grade 必须为整数型
    {
    case 4:
        cout << "该生期末等级为 : A";
        break;// 如果没有break则会把下面的语句都输出
    case 3:
        cout << "该生期末等级为 : B";
        break;
    case 2:
        cout << "该生期末等级为 : C";
        break;
    default :// 当以上条件都不满足时执行下列语句
        cout << "该生期末不及格,需要重修课程";
    }

    return 0;
}
 1 #include<iostream>
 2 using namespace std;
 3 int main() {
 4     int a;
 5     cout << "Please enter your score :" << endl;
 6     cin >> a;
 7     switch (a)
 8     {
 9     case 5 :
10         cout << "Congraduate !You get the A level !" << endl;
11         break;
12     case 4:
13         cout << "Wonderful ! You get the B level !" << endl;
14         break;
15     case 3:
16         cout << "C is you level .You need more hardworking ! " << endl;
17         break;
18     default:
19         cout << "oh ! no! You need test again." << endl;
20 
21     }
22     system("pause");
23 
24     return 0;
25 }

 

注意:case里如果没有break,那么程序会一直向下执行

if 和switch区别:
switch缺点:判断时候只能是整型或者字符型,不可以是一个区间
switch 优点:结构清晰,执行效率高

总结:与if语句比,对于多条件判断时,switch的结构清晰,执行效率高,缺点是switch不可以判断区间

posted on 2022-07-19 15:53  在野武将  阅读(161)  评论(0编辑  收藏  举报