tea asked in 電腦與網際網路程式設計 · 10 years ago

c++infix運算式

請問各位大大們:

1.要求使用者輸入一infix運算式,例如1+2*3。

2.印出此運算式的postfix結果,例如123*+。

3.再印出由postfix運算式的運算結果,例如7。

題目範圍

運算子:+,-,*,/

數字皆為正整數(大於0)

....................................................................................

想請各位大大們教我~

謝謝........

1 Answer

Rating
  • Wu
    Lv 5
    10 years ago
    Favorite Answer

    #include <iostream>

    using namespace std;

    #define SIZE 50

    #define PLUS -'+'

    #define MINUS -'-'

    #define MULTIPLY -'*'

    #define DIVISION -'/'

    int stack[SIZE];

    int stackptr=0;

    void ErrorExit(char *msg)

    { cout << "錯誤:" << msg << endl;

    system("pause");

    exit(1);

    }

    void Push(int data)

    { if (stackptr==SIZE)

    ErrorExit("推疊已滿!");

    stack[stackptr++]=data;

    }

    int Pop()

    { if (!stackptr)

    ErrorExit("推疊已空!");

    return stack[--stackptr];

    }

    int GetNextNum(char **ptr)

    { char num[10],i=0;

    while (**ptr == ' ' || **ptr == '\t') ++(*ptr);

    while (**ptr && **ptr >='0' && **ptr<='9') num[i++] = *((*ptr)++);

    num[i]=0;

    if (!i) ErrorExit("句式錯誤!");

    return atoi(num);

    }

    void Insert(int num, int op)

    { int tnum;

    tnum = Pop();

    if (!stackptr)

    { Push(tnum);

    Push(num);

    Push(op);

    return;

    }

    if (tnum == MINUS || tnum == PLUS)

    { Push(num);

    Push(op);

    }

    else Insert(num, op);

    Push(tnum);

    }

    int main()

    { char buf[255],*ptr, postfix[255]={0,};

    int i,num;

    while (1)

    { cout << "輸入算式(空返回結束):";

    fgets(buf,255,stdin);

    if (buf[0]=='\n') break;

    ptr = buf;

    while (*ptr && *ptr != '\n')

    { switch (ptr[0])

    { case '+':

    Push(GetNextNum(&(++ptr)));

    Push(PLUS);

    break;

    case '-':

    Push(GetNextNum(&(++ptr)));

    Push(MINUS);

    break;

    case '*':

    Insert(GetNextNum(&(++ptr)),MULTIPLY);

    break;

    case '/':

    Insert(GetNextNum(&(++ptr)),DIVISION);

    break;

    case ' ':

    case '\t':

    ++ptr;

    break;

    default:

    Push(GetNextNum(&ptr));

    break;

    }

    }

    for (i=0,postfix[0]=0; i<stackptr; ++i,strcat(postfix,buf))

    stack[i]<0 ? sprintf(buf,"%c ",abs(stack[i])) : sprintf(buf,"%d ",stack[i]);

    cout << "postfix=" << postfix << endl;

    stackptr=0;

    num=0;

    ptr = strtok(postfix," ");

    while (ptr)

    { switch (*ptr)

    { case '+':

    Push(Pop()+Pop());

    break;

    case '-':

    Push(-1*Pop()+Pop());

    break;

    case '*':

    Push(Pop()*Pop());

    break;

    case '/':

    Push((int)(1.0/Pop() * Pop()));

    break;

    default:

    Push(atoi(ptr));

    break;

    }

    ptr = strtok(NULL," ");

    }

    if (stackptr==1) cout << "結果=" << Pop() << endl;

    else ErrorExit("句式錯誤!");

    }

    system("pause");

    return 0;

    }

Still have questions? Get your answers by asking now.