繁体   English   中英

C 比较运算符优先级

[英]C Compare operator precedence

你好,我有一个方法叫

整数比较(字符 op1,字符 op2)

该方法将根据比较结果return 1, -1 or 0 (如果 op1 < op2,则为 1)。

我需要比较以下操作:

- 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;

枚举必须是标识符名称,而不是字符。 我建议将它们命名为PLUSMINUS等(另外,为什么%的优先级高于^事实上的标准是给予%*/相同的优先级。)

#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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM