# c++計算機程式(需顯示中序轉換後序過程)求救!(高點)

5+6*7

↓ ↓ 顯示後序法

567*+

↓ ↓在顯示輸出結果

47

### 1 個解答

• Wu
Lv 5
10 年前
最佳解答

這是第N次回答這問題

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

}

• 登入以對解答發表意見