四则运算
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define ADD1 sizeof(kuohao)
#define ADD2 50
typedef struct kuohao{char a;struct kuohao *pre;}kuohao;
char *creat()
{
char *a;
a=(char*)malloc(ADD2*sizeof(char));
gets(a);
return a;
}
int judgekuohao(char *a)
{
kuohao *top,*tail,*t;
top=tail=(kuohao*)malloc(ADD1);
while(*a!='\0')
{
if(*a=='(')
{
t=top;
top=(kuohao*)malloc(ADD1);
t->a='(';
top->pre=t;
}
else if(*a==')')
{
if(top==tail)
return -1;
else
{
t=top;
top=top->pre;
free(t);
}
}
a++;
}
if(top==tail)
return 1;
else return -1;
}
char precede(char a,char b)
{
int i,j;
char compare[8][8]={' ','+','-','*','/','(',')','\0',
'+','>','>','<','<','<','>','>',
'-','>','>','<','<','<','>','>',
'*','>','>','>','>','<','>','>',
'/','>','>','>','>','<','>','>',
'(','<','<','<','<','<','=',' ',
')','>','>','>','>',' ','>','>',
'\0','<','<','<','<','<',' ','='};
for(i=0;i<8;i++)
if(compare[0][i]==a)
break;
for(j=0;j<8;j++)
if(compare[j][0]==b)
break;
return compare[j][i];
}
void run(char *a)
{
int b[50]={0},count;char c[50],t;
int i=0,j=0;char *d;c[0]='\0';
while(*a!='\0'||c[j]!='\0')
{
count=0;
if(*a<='9'&&*a>='0')
{
d=a;
while(*d<='9'&&*d>='0')
{
d++;
count++;
}
while(count>0)
{
b[i]+=(int)((*a-'0')*pow(10,count-1));
count--;
a++;
}
i++;
}
else
{
switch(precede(*a,c[j]))
{
case'<':
j++;c[j]=*a;a++;break;
case'=':
j--;a++;break;
case'>':
t=c[j];
j--;i--;
if(t=='-')
{
b[i-1]=b[i-1]-b[i];
b[i]=0;
}
else if(t=='+')
{
b[i-1]=b[i-1]+b[i];
b[i]=0;
}
else if(t=='*')
{
b[i-1]=b[i-1]*b[i];
b[i]=0;
}
else if(t=='/')
{
b[i-1]=b[i-1]/b[i];
b[i]=0;
}
else break;
}
}
}
printf("%d\n",b[i-1]);
}
void main()
{
int i,n,s;
char *a[10],*t;
scanf("%d",&n);
for(i=0;i<=n;i++)
a[i]=creat();
for(i=1;i<=n;i++)
{
t=a[i];
s=judgekuohao(t);
if(s==-1)
{
printf("False\n");
continue;
}
else
run(a[i]);
}