?? sy3_2.c
字號:
/* sy3_2.c */
typedef char ElemType; /*定義字符類型*/
#include "SQstack.h"
SeqStack OPTR, OPND; /*定義前一個為操作符棧,后一個為操作數棧*/
char expr[255] = ""; /*存放表達式串*/
char *ptr = expr;
int step = 0; /*計算的步次*/
int In(char ch) /*判斷字符是否為運算符子程序*/
{return(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#');
}
void OutputStatus(void) /*打印當前棧內狀態及操作情況*/
{
int p;
printf("\n%-8d", ++step); /* step */
for(p = 0; p <= OPTR.top; p++)/* OPTR */
printf("%c",OPTR.elem[p]);
printf("\t");
for(p = 0; p <= OPND.top; p++)/* OPND */
if (step==1) printf("%c",' ');
else printf("%d ", OPND.elem[p]);
printf("\t\t%c", *ptr);
}
char Precede(char c1,char c2)
{/*判斷運算符優先級*/
int i=0,j=0;
static char array[49]={ '>', '>', '<', '<', '<', '>', '>',
'>', '>', '<', '<', '<', '>', '>',
'>', '>', '>', '>', '<', '>', '>',
'>', '>', '>', '>', '<', '>', '>',
'<', '<', '<', '<', '<', '=', '!',
'>', '>', '>', '>', '!', '>', '>',
'<', '<', '<', '<', '<', '!', '='};
switch(c1)
{
/*i為下面array的橫標*/
case '+' : i=0;break;
case '-' : i=1;break;
case '*' : i=2;break;
case '/' : i=3;break;
case '(' : i=4;break;
case ')' : i=5;break;
case '#' : i=6;break;
}
switch(c2)
{ /*j為下面array的縱標*/
case '+' : j=0;break;
case '-' : j=1;break;
case '*' : j=2;break;
case '/' : j=3;break;
case '(' : j=4;break;
case ')' : j=5;break;
case '#' : j=6;break;
}
return (array[7*i+j]); /*返回運算符*/
}
Operate(int a,char op,int b)
{ /*操作函數*/
OutputStatus();
printf("\tOPERATE(%d %c %d)", a, op, b);
switch(op) {
case '+' : return (a+b);
case '-' : return (a-b);
case '*' : return (a*b);
case '/' : return (a/b);
}
return 0;
}
int EvalExpr(void)
{
char c,theta,m,ch;
int a,b,x,y;
c = *ptr++;
GetTop(&OPTR,&ch);
while(c!='#'||ch!='#'){
if(!In(c))
{
m=atoi(&c);/*轉換為整型*/
Push_SeqStack(&OPND,m);
OutputStatus();
printf("\tPUSH(OPRD, %d)",m);
c = *ptr++;
}
else
{ GetTop(&OPTR,&ch);
switch(Precede(ch,c))
{
case '<':
Push_SeqStack(&OPTR,c);
OutputStatus();
printf("\tPUSH(OPRR,%c)",c);
c = *ptr++;
break;
case '=':
Pop_SeqStack(&OPTR,&ch);
OutputStatus();
printf("\tPOP(OPTR,%c)",ch);
c = *ptr++;
break;
case '>':
x=Pop_SeqStack(&OPTR,&ch);
if (x==OK) theta=ch;
y=Pop_SeqStack(&OPND,&ch);
if (y==OK) b=ch;
y=Pop_SeqStack(&OPND,&ch);
if (y==OK) a=ch;
Push_SeqStack(&OPND,Operate(a,theta,b));
break;
}/*switch*/
}/*else*/
GetTop(&OPTR,&ch);
}/*while*/
if (GetTop(&OPND,&ch)==OK)
return (ch);
}
int main(void)
{ printf("輸入一個表達式(以#結束):");
do{ gets(expr);
}while(!*expr); /*輸入合法的表達式字符串*/
InitStack_Sq(&OPTR); /*初始化操作符棧*/
OutputStatus();
printf("\tPUSH(OPRR,#)");
Push_SeqStack(&OPTR,'#'); /*將#壓入操作符棧*/
InitStack_Sq(&OPND ); /*初始化操作數棧*/
printf("\n\n結果是:%d\n", EvalExpr());
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -