分支语句的switch
当所有选项都可以用整数常量来标识时可以考虑用switch
/*
枚举结合switch
*/
#include<iostream>
enum {
red,
orange,
yellow,
green,
blue,
violet,
indigo,
};
using namespace std;
int main() {
cout << "input color code(0-6): ";
int code;
cin >> code;
while (code >= red && code <= indigo) {
switch (code)
{
case red:
cout << "red.\n";
break;
case orange:
cout << "orange.\n";
break;
case yellow:
cout << "yellow.\n";
break;
case green:
cout << "green.\n";
break;
case blue:
cout << "blue.\n";
break;
case violet:
cout << "violet.\n";
break;
case indigo:
cout << "indigo.\n";
break;
}
cout << "input color code(0-6): ";
cin >> code;
}
cout << "bye.\n";
return 0;
}
输出
input color code(0-6): 3
green.
input color code(0-6): 5
violet.
input color code(0-6): 2
yellow.
input color code(0-6): 8
bye.
|