📅  最后修改于: 2023-12-03 15:13:57.687000             🧑  作者: Mango
在C++中,switch语句是一种多分支选择结构,它可以根据表达式的值,跳转到与其匹配的分支语句执行,并继续往下执行,直到遇到break语句或者switch语句结束。
switch(expression)
{
case constant-expression:
statement(s);
break; //可选
case constant-expression:
statement(s);
break; //可选
//可选的default标签
default:
statement(s);
}
#include <iostream>
using namespace std;
int main()
{
int day = 4;
switch (day)
{
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day" << endl;
}
return 0;
}
输出结果:
Thursday
以上代码根据day变量的值进行switch case判断,输出星期四。