C语言:枚举类型 enum .2021-07-06

所谓 枚举  说人话就是:  一 一举列. 

说的再简单点就是  有一串数据 ,把 里面的东西一个个  的 计数 .

类似于各种如 学号 考号 等等编号,相当于另一个名字.我们在用真实的名字而各种系统的底层运转用的都是用着一个个数字代号进行处理

1.增加代码可读性

颜色选择

#include<stdio.h>

int main()
{
	enum COLOR{RED,YELLOW,GREEN};// 就像一串const int
	//enum 变量名{名字0(常量 int 0),名字1(常量 int 1)}

	int color=-1;
	char *colorName=NULL;
	
	scanf("%d",&color);

	switch(color)
	{
		case RED: colorName="red"; break;
		case YELLOW: colorName="yellow";break;
		case GREEN: colorName="green";break;
        //用单词替代 case:后面 抽象的数字,增加可读性

		default: colorName="unknown";break;
	}

	printf("you selected %s : ",colorName);

} 

2.自定义的数据类型

作为一种新的自定义的类型去使用.

#include<stdio.h>

enum color{red,YELLOW,GREEN};

int main()
{
	
	void f(enum color x);

	//做为自定义的数据类型使用
	enum color t = red;
	// enum color t = 0
	// 实际为整型数据参与运行

	scanf("%d",&t);
	f(t);
} 

void f(enum color x) { printf("%d ",x );}

#include<stdio.h>

enum COLOR{RED,YELLOW,GREEN,NumCOLORS};
//NumCOLORS 作为结束标记 和 总的数据数量
int main()
{

	int color=-1;
	char *colorName=NULL;//准备 接收符合要求的内容
	char *ColorNames[NumCOLORS]={"red","yellow","green"};
	
	scanf("%d",&color);//接收输入内容

	//筛选输入内容
	if (color>=RED && color<NumCOLORS) colorName=ColorNames[color];
	else colorName="unknow";
	
	printf("you selected %s : ",colorName);

} 

3.声明枚举量时指定值

#include<stdio.h>

enum COLOR{RED=1,YELLOW,GREEN=5,NumCOLORS};
//指定值,指定值后的值若未指定,则为 前一指定值+1
int main()
{

	printf("you selected %d : ",YELLOW);

} 

4.赋一个整数值???

#include<stdio.h>

enum COLOR{RED=1,YELLOW,GREEN=5,NumCOLORS};
//指定值,指定值后的值若未指定,则为 前一指定值+1
int main()
{
	enum COLOR text=0;
	printf("you selected %d : ",text);

} 

5.查询水果价格

C语言:实验3-5 查询水果价格.2021-07-17_慕容雪羽-CSDN博客

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mklpo147

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值