【问题标题】:C Compare operator precedenceC比较运算符优先级
【发布时间】:2011-05-26 01:04:12
【问题描述】:

你好,我有一个方法叫

int 比较(char op1, char op2)

该方法将return 1, -1 or 0 取决于比较的结果。 (如果 op1

我需要比较以下操作:

- subtraction
* multiplication
/ division
^ exponentiation
% remainder

我考虑过使用枚举,例如:

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

但这不会编译。有人可以帮忙吗?

【问题讨论】:

  • 所以比较是优先顺序?

标签: c enums operators compare operator-precedence


【解决方案1】:

你不能使用字符作为枚举的键,你应该这样做:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      #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));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        相关资源
        最近更新 更多