C比较运算符优先级

C比较运算符优先级,c,enums,operators,compare,operator-precedence,C,Enums,Operators,Compare,Operator Precedence,嗨,我有一个方法叫 int比较(字符op1,字符op2) 根据比较结果,该方法将返回1、-1或0。(如果op1相同的优先级)枚举必须是标识符名称,而不是字符。我建议将它们命名为加,减,等等。(还有,为什么%比^具有更高的优先级?事实上的标准是给%赋予与*和//code>相同的优先级)\ 结构优先 { char op; int-prec; }进位[]= { { '+', 1 }, { '-', 1 }, { '*', 2 }, { '/', 2 }, { '^', 3 }, { '%', 4 },

嗨,我有一个方法叫

int比较(字符op1,字符op2)

根据比较结果,该方法将
返回1、-1或0
。(如果op1 我需要比较以下操作:

- subtraction
* multiplication
/ division
^ exponentiation
% remainder
我已考虑使用枚举,例如:

enum ops{
    '+'=1, '-'=1, '*'=2, '/'=2, '^', '%'
}var;

但这并没有编译。有人可以帮忙吗?

您不能使用字符作为枚举的键,您应该执行以下操作:

enum ops {
    OP_PLUS       = 1,
    OP_MINUS      = 1,
    OP_MULT       = 2,
    OP_DIV        = 2,
    OP_POWER,
    OP_MOD
} var;

不能将字符用作枚举的键,应执行以下操作:

enum ops {
    OP_PLUS       = 1,
    OP_MINUS      = 1,
    OP_MULT       = 2,
    OP_DIV        = 2,
    OP_POWER,
    OP_MOD
} var;

枚举必须是标识符名称,而不是字符。我建议将它们命名为
加号
减号
,等等。(还有,为什么
%
的优先级高于
^
?事实上的标准是赋予
%
*
//code>相同的优先级)

枚举必须是标识符名称,而不是字符。我建议将它们命名为
,等等。(还有,为什么
%
^
具有更高的优先级?事实上的标准是给
%
赋予与
*
//code>相同的优先级)

\
结构优先
{
char op;
int-prec;
}进位[]=
{ { '+', 1 },
{ '-', 1 },
{ '*', 2 },
{ '/', 2 },
{ '^', 3 },
{ '%', 4 },
{ 0, 0 }};
整数比较(字符*a,字符*b)
{
int prec_a=0,prec_b=0,i;
对于(i=0;前置[i].op&(!prec_a | | |!prec_b);i++)
{
if(a==先行[i].op)
prec_a=频率[i].prec;
if(b==前向[i].op)
prec_b=频率[i].prec;
}
如果(!prec_a | | |!prec_b)
{
fprintf(stderr,“找不到运算符%c和/或%c\n”,a,b);
回报率(-2);
}
如果(预处理a<预处理b)
返回-1;
if(prec_a==prec_b)
返回0;
返回1;
}
main()
{
字符a,b;
a='+';b='-';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='+';b='*';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='+';b='^';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='+';b='%';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='*';b='+';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='^';b='+';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='%';b='+';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
}
#包括
结构优先
{
char op;
int-prec;
}进位[]=
{ { '+', 1 },
{ '-', 1 },
{ '*', 2 },
{ '/', 2 },
{ '^', 3 },
{ '%', 4 },
{ 0, 0 }};
整数比较(字符*a,字符*b)
{
int prec_a=0,prec_b=0,i;
对于(i=0;前置[i].op&(!prec_a | | |!prec_b);i++)
{
if(a==先行[i].op)
prec_a=频率[i].prec;
if(b==前向[i].op)
prec_b=频率[i].prec;
}
如果(!prec_a | | |!prec_b)
{
fprintf(stderr,“找不到运算符%c和/或%c\n”,a,b);
回报率(-2);
}
如果(预处理a<预处理b)
返回-1;
if(prec_a==prec_b)
返回0;
返回1;
}
main()
{
字符a,b;
a='+';b='-';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='+';b='*';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='+';b='^';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='+';b='%';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='*';b='+';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='^';b='+';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
a='%';b='+';printf(“Prec%c%c是%d\n”,a,b,比较(a,b));
}

那么比较是优先顺序?那么比较是优先顺序?