我对 C 很陌生,我得到了以下说明:
“将枚举数据类型 dfaState 转换为 int 类型;因此,变量 state 应该是 int 变量。另外,将枚举值 EE、OE、OO 和 EO 分别映射到整数常量 0、1、2 和 3。”
这是我得到的代码:
#include <stdio.h>
enum dfaState { EE, OE, OO, EO };
enum dfaState state = EE;
char input;
int main(void)
{
//main function here
}
我应该如何处理这些说明?我试过这个:
#include <stdio.h>
int EE = 0;
int OE = 1;
int OO = 2;
int EO = 3;
int state;
char input;
int main(void)
但我收到错误。如有任何帮助,我们将不胜感激。
最佳答案
来自 C11 标准:
C11 (n1570), § 6.7.2.2 Enumeration specifiers
Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.
这意味着在 C 中,枚举基础类型已经是整型:您的代码已经执行了它应该执行的操作:您可以更明确地分别使用值 0、1、2、3:
#include <stdio.h>
enum dfaState {
EE = 0,
OE = 1,
OO = 2,
EO = 3
};
enum dfaState state = EE;
int main(void) {
printf("dfaState %d\n", state); // will print "0"
return 0;
}
关于c - 枚举数据类型转换为int类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33227581/