# 用C實作簡易計算機

 運算子：+,-,*,/

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

Rating
• Wu
Lv 5

#define SIZE 50

#define PLUS -'+'

#define MINUS -'-'

#define MULTIPLY -'*'

#define DIVISION -'/'

int stack[SIZE];

int stackptr=0;

void ErrorExit(char *msg)

{ cout << "Error:" << msg << endl;

system("pause");

exit(1);

}

void Push(int data)

{ if (stackptr==SIZE)

ErrorExit("Stack Full!");

stack[stackptr++]=data;

}

int Pop()

{ if (!stackptr)

ErrorExit("Stack Empty!");

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("Syntax Error!");

return atoi(num);

}

void Insert(int num, int op)

{ int tnum;

tnum = Pop();

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(-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("Syntax Error!");

}

system("pause");

return 0;

}

2010-05-11 09:47:52 補充：

有一些錯誤, Insert 改為:

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

}

2010-05-11 09:48:03 補充：

另外:

Push(-Pop() + Pop());

改為:

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