2011-05-26 47 views
0

您好我有一個稱爲Ç比較算符優先

INT比較方法(炭OP1,OP2炭)

該方法將return 1, -1 or 0取決於比較的結果。 (如果op1 < op2則爲1)。

我需要比較以下操作:

- subtraction 
* multiplication 
/division 
^ exponentiation 
% remainder 

我一直在使用一個枚舉考慮,如:

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

但這並不編譯。任何人都可以伸出援手嗎?

+0

因此比較是優先順序嗎? – 2011-05-26 01:08:28

回答

3

不能使用字符鍵的枚舉,你應該這樣做:

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

枚舉必須標識符名稱,而不是字符。我建議命名它們​​,MINUS,等等(還有,爲什麼會%具有更高的優先級比^嗎?事實上標準是給%相同的優先級爲*/。)

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