#include<stdio.h>
#include<malloc.h>
#include<math.h>
typedef char ElemType ;
#define MAXSIZE 30
typedef struct
{ ElemType elem[MAXSIZE];
int top;
}SeqStack;
SeqStack A,B; /*定義前一個為運算子堆疊,后一個為運算元堆疊*/
char a[255] = ""; /*存放運算式串*/
void InitStack_Sq(SeqStack *s) /*初始化堆疊操作*/
{s->top=-1;
}
int Empty_Sq(SeqStack *s) /*判堆疊是否為空*/
{return (s->top==-1);
}
int Push_SeqStack(SeqStack *s, ElemType x)
{if (s->top==MAXSIZE-1) return -1 ; /* 堆疊滿不能入堆疊 */
else { s->top++;
s->elem[s->top]=x ;
return 1;
}
}
int Pop_SeqStack(SeqStack *s, ElemType *y)
{ if (Empty_Sq(s)) return -1; /* 堆疊空不能出堆疊 */
else
{ *y=s->elem[s->top];
s->top--; return 1;} /* 堆疊頂元素存入*y,回傳 */
}
ElemType GetTop(SeqStack *s,ElemType *y) /*取頂元素*/
{if (Empty_Sq(s)) return -1; /* 堆疊空不能出堆疊 */
else { *y=s->elem[s->top];
return 1;
}
}
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]); /*回傳運算子*/
}
int Operate(double a,char op,double b)
{ /*操作函式*/
switch(op) {
case '+' : return (a+b);
case '-' : return (b-a);
case '*' : return (a*b);
case '/' : return (b/a);
case '^': return (int)pow(b,(double)a);
}
return 0;
}
int In(char ch) /*判斷字符是否為運算子子程式*/
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='^')
return 1;
else
return 0;
}
int process(char a[255])
{
int i=0,temp=0,m=0,y,x,flag=0,glag=0,hlag=0;
char ch;
while(a[i]!=NULL)
{
if(In(a[i]))
{
if (Empty_Sq(&A))
{
Push_SeqStack(&A,a[i]);
glag=1;
}
if(glag==0)
{
GetTop(&A,&ch);
switch(Precede(ch,a[i]))
{
case '<':
Push_SeqStack(&A,a[i]);
break;
case '=':
Pop_SeqStack(&A,&ch);
break;
case '>':
flag=1;
Pop_SeqStack(&B,&ch);x=ch;
Pop_SeqStack(&B,&ch);y=ch;
Pop_SeqStack(&A,&ch);
m=Operate(x,ch,y);
Push_SeqStack(&B,m);
GetTop(&B,&ch);
printf("%d\n",ch);
break;
}
} glag=0;
}
else
{
temp=a[i]-'0';
Push_SeqStack(&B,temp);
}
if(flag==0)
i++;
flag=0;
}
while(A.top!=-1)
{
Pop_SeqStack(&B,&ch);
x=ch;
Pop_SeqStack(&B,&ch);
y=ch;
Pop_SeqStack(&A,&ch);
m=Operate(x,ch,y);
Push_SeqStack(&B,m);
GetTop(&B,&ch);
printf("%d\n",ch);
}
Pop_SeqStack(&B,&ch);
return ch;
}
int main ()
{
int num=0;
gets(a);
InitStack_Sq(&A);
InitStack_Sq(&B);
num=process(a);
printf("%d",num);
}
uj5u.com熱心網友回復:
是什么錯誤?uj5u.com熱心網友回復:
沒報錯,但就是算不出來。。。我也不知道哪錯了1+(3+2)*(7^2+6*9)/(2)算這個式子的時候到倒數第二步就結果不對轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/60188.html
標籤:C語言
上一篇:C語言小白在線求教關于指標的練習,C語言牛逼。各位大神幫忙看看。
下一篇:新手 求大佬幫忙
