*num=numstack->array[numstack->top-1];
numstack->top--;
}
void pushop(opstack *opstack,char op){
opstack->top++;
opstack->array[opstack->top-1]=op;
}
void popop(opstack *opstack,char *op){
*op=opstack->array[opstack->top-1];
opstack->top--;
}
double calc(double a,double b,char c){
double result;
switch(c){
case '+':result=a+b;break;
case '-':result=a-b;break;
case '*':result=a*b;break;
case '/':result=a/b;break;
}
return result;
}
char priority(char y,char x){
char priority='<';
switch(x){
case '+':
case '-':if(y=='(' || y=='#')priority='>';break;
case '*':
case '/':if(y=='(' || y=='#'|| y=='+' || y=='-')priority='>';break;
case '(':priority='>';break;
case ')':if(y=='(')priority='=';break;
case '#':if(y=='#')priority='=';break;
default:priority='e';
}
return priority;
}
void process(numstack *numstack,opstack *opstack,char x){
double a,b;char c;
static double tempnum=0.00000000;static int len=10;static int dot=0,flags=0;
if(isdigit(x) || x=='.'){
if(x=='.')dot=1;
else{
if(dot==0)
tempnum=tempnum*10+cint(x);
else{
tempnum=tempnum+(double)cint(x)/len;
len*=10;
}
}
}
else{
if(flags==0 && x!='('){pushnum(numstack,tempnum);tempnum=0.00000000;len=10;dot=0;}
switch(priority(opstack->array[opstack->top-1],x)){
case '>':pushop(opstack,x);flags=0;break;
case '<':
popop(opstack,&c);
popnum(numstack,&b);
popnum(numstack,&a);
pushnum(numstack,calc(a,b,c));flags=1;
process(numstack,opstack,x);break;
case '=':popop(opstack,&c);flags=1;break;
default:printf("wrong express!");exit(0);
}
}
}
main(){
numstack numstack;opstack opstack;char s[n];int i=0;
numstack.top=0;opstack.top=0;
pushop(&opstack,'#');
printf("\nenter your expression and end it with #:");scanf("%s",s);
for(i=0;i<strlen(s);i++)
process(&numstack,&opstack,s[i]);
printf("the result is %f",numstack.array[numstack.top-1]);