四则运算用c语言怎么搞

要求:实现带有括号的四则运算,输入是一个带有括号的四则运算表达式,输出是计算得出的正确计算结果。

#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]);
}
} 输入: 第一行输入要计算的算术表达式的个数n 后紧跟n行算术表达式
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-05
什么带括号...说清楚
相似回答
大家正在搜