利用栈的性质,编写一个能四则运算程序,支持括号+ - * /,输入完后以#号结束,只支持个位数的计算
例如 1+2+3*(4+5)#
#include <stdio.h> #define MAXNUM 100 #define FALSE 0 #define TRUE 1 struct sqstack{ int stack[MAXNUM]; int top; }optr,opnd;
int initstack (struct sqstack *s) { s->top=-1 ; return TRUE; }
int push (struct sqstack *s,int x) { if (s->top>MAXNUM-1) return FALSE; s->top++; s->stack[s->top]=x; return TRUE; }
int pop (struct sqstack *s) { int x; if (s->top<0) return NULL; x=s->stack[s->top]; s->top--; return x; }
int gettop (struct sqstack *s) { if (s->top<0) return NULL; return (s->stack[s->top]); }
int operate (int n1,int s,int n2) { switch (s) { case '+' :return (n1-48)+(n2-48)+48; case '-' :return (n1-48)-(n2-48)+48; case '*' :return (n1-48)*(n2-48)+48; case '/' :return (n1-48)/(n2-48)+48; } }
int precede (int a,int b) { switch (a) { case '+': case '-': switch (b) { case '+': case '-': case ')': case '#': return '>'; case '*': case '/': case '(': return '<'; };break; case '*': case '/': switch (b) { case '+': case '-': case '*': case '/': case ')': case '#': return '>'; case '(': return '<'; };break; case '(': switch (b) { case '+': case '-': case '*': case '/': case '(': return '<'; case ')': return '='; case '#': return FALSE; };break; case ')': switch (b) { case '+': case '-': case '*': case '/': case ')': case '#': return '>'; case '(': return FALSE; };break; case '#': switch (b) { case '+': case '-': case '*': case '/': case '(': return '<'; case '#': return '='; case ')': return FALSE; };break; } }
int isoptr (char op) { if (op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'||op=='#') return TRUE; return FALSE; }
main () { int a,b,op; char c,d; insert: printf ("Please input a expression:\n"); initstack (&optr); push (&optr,'#'); initstack (&opnd); scanf ("%c",&c); while (c!='#'||gettop(&optr)!='#') { if (isoptr(c)==FALSE) { push(&opnd,c); scanf ("%c",&c);} else switch (precede (gettop(&optr), c)) { case '<': push(&optr,c); scanf ("%c",&c); break; case '=': pop(&optr); scanf ("%c",&c); break; case '>': op=pop(&optr); b=pop(&opnd); a=pop(&opnd); push(&opnd,operate(a,op,b)); break; } } printf ("The answer is %d\n",gettop(&opnd)-48); printf ("\nPress any to continue and 'q' to quit\n\n"); d=getch(); if (d=='q') exit (); else goto insert;
}
[此贴子已经被作者于2004-09-24 15:30:49编辑过]