c语言计算器的一些问题
计算器的目标:可以进行四则运算,可区分它们之间的优先关系,并且可识别小括号。我的主要思路是采用栈的结构,将运算符和数字分别送入两个不同的栈中,进行操作;现在代码中存在的问题是在有优先级判断的条件下,仍然出现盲目的从左至右的运算,再一个问题就是一旦有减法参与,程序就会得不到结果。请大家帮忙分析一下,由于刚刚学习的结构代码有些啰嗦,请见谅。
#include<stdio.h>
#include<stdlib.h>
#define NUMBER 10//栈大小的单位
struct Spstack{
int *base;
int *top;
int stacksize;
}s;//s为数字栈
struct Zpstack{
char *base;
char *top;
int stacksize;
}z;//z为操作符栈
int ZInitstack()//Z创建栈
{
z.base=(char*)malloc(sizeof(char)*NUMBER);
if(!z.base)exit(1);
z.top=z.base;
z.stacksize=NUMBER;
return (1);
}
char ZPop()//Z出栈
{
char e;
if(z.base==z.top)return (-1);
e=*--z.top;
return e;
}
int ZPush(char e)//Z入栈
{
if (z.top-z.base>=z.stacksize)
{
z.base=(char*)realloc(z.base,(NUMBER+z.stacksize)*(sizeof(char)));
if (!z.base)exit(1);
z.top=z.base+z.stacksize;
z.stacksize+=NUMBER;
printf("done");
}
*z.top++=e;
return 1;
}
char ZGettop()
{
char c;
if(z.base==z.top)return -1;
c=*(z.top-1);
return c;
}
int StackEmpty(Spstack s)//判断空栈
{
if(s.base==s.top)return 1;
else return 0;
}
int SInitstack()//S创建栈
{
s.base=(int*)malloc(sizeof(int)*NUMBER);
if(!s.base)exit(1);
s.top=s.base;
s.stacksize=NUMBER;
return (1);
}
int SPop()//S出栈
{
int e;
if(s.base==s.top)return (-1);
e=*--s.top;
return e;
}
int SPush(int e)//S入栈
{
if (s.top-s.base>=s.stacksize)
{
s.base=(int*)realloc(s.base,(NUMBER+s.stacksize)*(sizeof(int)));
if (!s.base)exit(1);
s.top=s.base+s.stacksize;
s.stacksize+=NUMBER;
printf("done");
}
*s.top++=e;
return 1;
}
int SGettop()
{
int c;
if(s.base==s.top)return -1;
c=*(s.top-1);
return c;
}
int choose(char c,char d)//判断优先级从从大到小:( */ +- ) #
{
if(c=='#'&&d=='#')return 2;
else if(c==d) return 3;
else if(c=='('&&d!=')') return 3;
else if(c=='*'||c=='/'&&d!='(') return 3;
else if(c=='+'||c=='-'&&d==')') return 3;
else if(c=='('&&d==')')return 2;
else return 1;
}
int Operate(int a,char c,int b)
{
switch(c)
{
case '+':return (a+b);
case '-':return (a-b);
case '*':return (a*b);
case '/':return (a/b);
}
}
int calculation()
{
int flag=0,i,sum=0,a=0,b=0;
char c,thrta,number[8]={'*','*','*','*','*','*','*','*'};
ZInitstack();
SInitstack();
ZPush('#');
c=getchar();
while(c!='#'||ZGettop()!='#')
{
if(c>47&&c<58)
if(flag==0)
{
for(i=0;i<8;i++)number[i]='*';
i=0;
number[i++]=c;
flag=1;
c=getchar();
}
else {number[i++]=c;c=getchar();}
else
{
switch (choose(ZGettop(),c))
{
case 1:
if(flag==0){ZPush(c);c=getchar();}
else
{
flag=0;
for(i=0;number[i]!='*';i++)
sum=sum*10+number[i]-48;
SPush(sum);
ZPush(c);
sum=0;
c=getchar();
}
printf("d1");
break;
case 2:
if(flag==0)ZPop();
else
{
flag=0;
for(i=0;number[i]!='*';i++)
sum=sum*10+number[i]-48;
SPush(sum);
ZPop();
sum=0;
c=getchar();
}
printf("d2");
break;
case 3:
thrta=ZPop();
if(flag==0);
else
{
flag=0;
for(i=0;number[i]!='*';i++)
sum=sum*10+number[i]-48;
SPush(sum);
sum=0;
}
b=SPop();
a=SPop();
SPush(Operate(a,thrta,b));
printf("d3");
break;
}
}
printf("d0");
}
return (SGettop());
}
int main(void)
{
int s;
while (1)
{
printf("请输入算式:\n");
s=calculation();
printf("运算结果:%d\n",s);
}
system("pause");
return 0;
}