示例一
以下是一些关于 switch、while、do…while、break 和 continue 这些知识点的C++示例代码:
1. switch 语句示例
#include <iostream>
using namespace std;
int main() {
int day;
cout << "请输入星期几(1-7):";
cin >> day;
switch (day) {
case 1:
cout << "星期一" << endl;
break;
case 2:
cout << "星期二" << endl;
break;
case 3:
cout << "星期三" << endl;
break;
case 4:
cout << "星期四" << endl;
// 注意这里没有break,会导致fall-through到下一个case
case 5:
cout << "星期五或由于fall-through也执行的星期四之后的星期五" << endl;
break;
case 6:
cout << "星期六" << endl;
break;
case 7:
cout << "星期日" << endl;
break;
default:
cout << "无效输入" << endl;
}
return 0;
}
2. while 循环示例
#include <iostream>
using namespace std;
int main() {
int count = 1;
while (count <= 5) {
cout << "计数:" << count << endl;
count++;
}
return 0;
}
3. do…while 循环示例
#include <iostream>
using namespace std;
int main() {
int count = 1;
do {
cout << "计数(do...while):" << count << endl;
count++;
} while (count <= 5);
return 0;
}