1. switch语句中的每一个case标签都必须是一个单独的值。
2.这个值必须是整数或者是char类型的字母,因此switch语句无法处理浮点测试。
3. case标签值还必须是常量。
4. 如果选项涉及取值范围、浮点测试或两个变量的比较,则应使用if else语句。
5. 当选项超过两个的话,建议使用switch语句,因为代码长度相对精简,执行速度高,处理起来更有效率。例子如下:
#include <iostream>
using namespace std;
int main()
{
int day;
cin >> day;
switch (day)
{
case 7:
cout << "sunday" << endl;
break;
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;
default:
cout << "Day out of range sunday" << endl;
break;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int age, index;
cin >> age;
if (age > 17 && age < 35)
index = 0;
else if (age >= 35 && age < 50)
index = 1;
else if (age >= 50 && age < 65)
index = 2;
else
index = 3;
cout << index << endl;
return 0;
}
参考文献:C++ Primer Plus第六版