/*中缀表达式计算:中缀表达式为 (a+b)*c
中缀表达式储存在数组A[]中,创建栈stack1[]用来存放运算符,从数组中取出字符:
如果是’+’ ‘-’,栈顶元素出栈,直到栈空或者 ‘**’ ‘/’,再入栈
如果是 * ‘/’,如果栈顶是 * /,出栈直到栈空或者 * /,再入栈
如果是’(‘入栈
如果是’)'出栈直到遇到 ‘(’
创建stack2[ ]用来存放数字
注意字符类型转换 */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double calcu(double a,double b,char c)
{
switch(c)
{
case'+':return a+b;
case'-':return a-b;
case'*':return a*b;
case'/':return a/b;
}
}
double fun(char A[])
{
char c;
char stack1[N];
int top1=-1,top2=-1;
double stack2[N];
double a,b,result;
int i=0;
while(A[i]!='\0')
{
if(A[i]=='*' || A[i]=='/')
{
if(top1==-1)
{
stack1[++top1]=A[i];
}
else
{
while(stack1[top1]=='*' ||stack1[top1]=='/')
{
a=stack2[top2--];
b=stack2[top2--];
c=stack1[top1--];
result=calcu(b,a,c);
stack2[++top2]=result;
}
stack1[++top1]=A[i];
}
}
else if(A[i]=='+' || A[i]=='-')
{
if(top1==-1)
{
stack1[++top1]=A[i];
}
else
{
while(stack1[top1]=='*' ||stack1[top1]=='/' ||stack1[top1]=='+' ||stack1[top1]=='-')
{
a=stack2[top2--];
b=stack2[top2--];
c=stack1[top1--];
result=calcu(b,a,c);
stack2[++top2]=result;
}
stack1[++top1]=A[i];
}
}
else if(A[i]==')')
{
while(stack1[top1]!='(')
{
a=stack2[top2--];
b=stack2[top2--];
c=stack1[top1--];
result=calcu(b,a,c);
stack2[++top2]=result;
}
--top1;
}
else if(A[i]=='(')
{
stack1[++top1]=A[i];
}
else
{
stack2[++top2]=A[i]-'0';
}
i++;
}
while(top1!=-1) //如果还有剩余的操作符继续计算
{
a=stack2[top2--];
b=stack2[top2--];
c=stack1[top1--];
result=calcu(b,a,c);
stack2[++top2]=result;
}
return stack2[top2];
}
int main()
{
char A[]="(4+2*3)/4";
double result=fun(A);
printf("%f",result);
return 0;
}