一、枚举类型的定义
enum 类型名 {枚举值表};
类型名是变量名,指定枚举类型的名称。
枚举值表也叫枚举元素列表,列出定义的枚举类型的所有可用值,各个值之间用“,”分开。
例:
enum Suit { Diamonds, Hearts, Clubs, Spades };
二、枚举变量说明
枚举变量有多种声明方式:
1.枚举类型定义与变量声明分开
如:
enum Suit { Diamonds, Hearts, Clubs, Spades };
enum Suit a;
enum Suit b,c;
变量a,b,c的类型都定义为枚举类型enum Suit。
1 2 3 4 5 6 7 8 | include <iostream> using namespace std; enum color{black, blue,green,cyan,red,purple,yellow,white}; color tag; int main(){ tag=yellow; cout<<tag; } |
题目:口袋中有红,黄,蓝,白,黑5种颜色球若干个。每次从口袋中取出3个不同颜色的球,问有多少种取法?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include<iostream> using namespace std; enum colors {red,yello,blue,white,black};//定义球的枚举类型 colors color1; void transfer(int l)//将相应的数值组合通过switch语句转换为字符串 { color1=(colors)l; switch (color1) { case red:cout << "red "; break; case yello:cout << "yello "; break; case blue:cout << "blue "; break; case white:cout << "white "; break; case black:cout << "black "; break; } } int main() { int i, j, k; int count=0; for ( i = red; i <= black; i++) { for (j = i+1; j <= black; j++) { for (k =j+1; k <= black; k++) { transfer(i); transfer(j); transfer(k); cout <<endl; count++; } } } cout << count; return 0; } |