C比较运算符优先级

| 嗨,我有一个方法叫做   int compare(char op1,char op2) 该方法将根据比较结果为“ 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;
    
枚举必须是标识符名称,而不是字符。我建议将它们命名为
PLUS
MINUS
等(而且,为什么ѭ6precede的优先级比
^
高?事实上的标准是给
%
赋予与
*
/
相同的优先级。)     
#include <stdio.h>

struct precedence
{
  char op;
  int prec;
} precendence[] =
{ { \'+\', 1 },
  { \'-\', 1 },
  { \'*\', 2 },
  { \'/\', 2 },
  { \'^\', 3 },
  { \'%\', 4 },
  { 0, 0 }};

int compare(char *a, char *b)
{
  int prec_a = 0, prec_b = 0, i;

  for(i=0; precendence[i].op && (!prec_a || !prec_b); i++)
  {
    if (a == precendence[i].op)
      prec_a = precendence[i].prec;
    if (b == precendence[i].op)
      prec_b = precendence[i].prec;
  }

  if (!prec_a || !prec_b)
  {
    fprintf(stderr,\"Could not find operator %c and/or %c\\n\",a,b);
    return(-2);
  }
  if (prec_a < prec_b)
    return -1;
  if (prec_a == prec_b)
    return 0;
  return 1;
}


main()
{
  char a,b;

  a=\'+\'; b=\'-\'; printf(\"Prec %c %c is %d\\n\", a,b,compare(a,b));
  a=\'+\'; b=\'*\'; printf(\"Prec %c %c is %d\\n\", a,b,compare(a,b));
  a=\'+\'; b=\'^\'; printf(\"Prec %c %c is %d\\n\", a,b,compare(a,b));
  a=\'+\'; b=\'%\'; printf(\"Prec %c %c is %d\\n\", a,b,compare(a,b));
  a=\'*\'; b=\'+\'; printf(\"Prec %c %c is %d\\n\", a,b,compare(a,b));
  a=\'^\'; b=\'+\'; printf(\"Prec %c %c is %d\\n\", a,b,compare(a,b));
  a=\'%\'; b=\'+\'; printf(\"Prec %c %c is %d\\n\", a,b,compare(a,b));
}
    

要回复问题请先登录注册