“C语言中的枚举常量”的版本间的差异
		
		
		
		
		
		跳到导航
		跳到搜索
		
				
		
		
	
Jihongchang(讨论 | 贡献)  | 
				Jihongchang(讨论 | 贡献)   | 
				||
| (未显示同一用户的1个中间版本) | |||
| 第16行: | 第16行: | ||
#include<stdio.h>  | #include<stdio.h>  | ||
| − | enum week { mon = 1, tue = 2, wed = 3, thu = 4, fri = 5, sat = 6, sun = 7 };  | + | enum week    | 
| + | {    | ||
| + | 	mon = 1,    | ||
| + | 	tue = 2,    | ||
| + | 	wed = 3,    | ||
| + | 	thu = 4,    | ||
| + | 	fri = 5,    | ||
| + | 	sat = 6,    | ||
| + | 	sun = 7    | ||
| + | };  | ||
int main()  | int main()  | ||
| 第30行: | 第39行: | ||
</syntaxhighlight>枚举只能声明整型  | </syntaxhighlight>枚举只能声明整型  | ||
| + | |||
| + | |||
| + | <syntaxhighlight lang="c">  | ||
| + | #include<stdio.h>  | ||
| + | |||
| + | enum week  | ||
| + | {  | ||
| + | 	mon = 1,  | ||
| + | 	tue,  | ||
| + | 	wed,  | ||
| + | 	thu,  | ||
| + | 	fri,  | ||
| + | 	sat,  | ||
| + | 	sun  | ||
| + | };  | ||
| + | |||
| + | int main()  | ||
| + | {  | ||
| + | 	enum week wx;  | ||
| + | 	wx = mon;  | ||
| + | 	wx = tue;  | ||
| + | 	printf("%d \n", wx);  | ||
| + | 	wx = sun;  | ||
| + | 	printf("%d \n", wx);  | ||
| + | 	return 0;  | ||
| + | }  | ||
| + | </syntaxhighlight><syntaxhighlight lang="console">  | ||
| + | 2  | ||
| + | 7  | ||
| + | </syntaxhighlight>如上,只给一个枚举值,之后的枚举值不给,默认依次递增1。  | ||
2022年10月30日 (日) 06:22的最新版本
https://www.bilibili.com/video/BV1vR4y1H7MY/?p=12
以星期为例:
#include<stdio.h>
// mon = 1, tue = 2, wed = 3, thu = 4, fri = 5, sat = 6, sun = 7
int main()
{
	int wx; // 1 2 3 4 5 6 7
	wx = 1;
	wx = 7;
	wx = 9; //实际没有9对应周几
	printf("%d \n", wx);
	return 0;
}
如上,有时候我们需要限制取值的范围。
#include<stdio.h>
enum week 
{ 
	mon = 1, 
	tue = 2, 
	wed = 3, 
	thu = 4, 
	fri = 5, 
	sat = 6, 
	sun = 7 
};
int main()
{
	enum week wx;
	wx = mon;
	wx = sun;
	printf("%d \n", wx);
	return 0;
}
7
枚举只能声明整型
#include<stdio.h>
enum week
{
	mon = 1,
	tue,
	wed,
	thu,
	fri,
	sat,
	sun
};
int main()
{
	enum week wx;
	wx = mon;
	wx = tue;
	printf("%d \n", wx);
	wx = sun;
	printf("%d \n", wx);
	return 0;
}
2
7
如上,只给一个枚举值,之后的枚举值不给,默认依次递增1。