C语言表达式计算器代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#include
typedef struct Expression//定义表达式结构体
{
int num[64];
char ch[64];
}Exper;
typedef struct node //定义字栈
{
char e[100];
int top;
}linkstack;
typedef struct Node //定义整数栈
{
int c[100];
int top;
}link;
char precede(char a,char b) //符号判断
{
int i=0,j=0;
char sign[]="+-*/()^%";
char
prec[8][8]={">><<()<<",">><<()<<",">>>>()<<",">>>>()<<","((((~~((","))))~~))",">>>>()>>",">>>>()> >"};
if (b=='=')
{
return 0;
}
while(sign[i]!=a)
{
i++;
}
while (sign[j]!=b)
{
j++;
}
return(prec[i][j]);
}
void push1(linkstack *p,char c) //字符入栈
{
p->e[p->top++]=c;
}
void push2(link *p,int num) //整数入栈
{
p->c[p->top++]=num;
}
char gettop(linkstack *s) //读字符栈顶的元素{
char c;
c=s->e[s->top-1];
return(c);
}
char pop1(linkstack *s) //字符出栈{char c;
c=s->e[--s->top];
return(c);
}
int pop2(link *N) //整数入栈
{
int num;
num=N->c[--N->top];
return(num);
}
int operate(int a, char oper,int b)//进行运算
{
int num;
switch (oper)
{
case '+': num=a+b;break;
case '-': num=a-b;break;
case '*': num=a*b;break;
case '/': num=a/b;break;
case '^': num=pow(a,b);break;
case '%': num=a%b;break;
}
return num;
}
Exper number(char *n_w) //把输入的字符转换成整数和字符,并分别存在数组中
{
int i=0;
int j=0;
int k=0;
int temp;
Exper n_exper;
while (n_w[i]!='\0')
{
if (n_w[i]>='0'&& n_w[i]<='9')
{
temp=n_w[i]-'0';
i++;
while (n_w[i]>='0'&& n_w[i]<='9')
{
temp=temp*10+n_w[i]-'0';
i++;
}
n_exper.num[j]=temp;
j++;
}
n_exper.ch[k]=n_w[i];
k++;
i++;
}
return n_exper;
}
void Calculate(Exper C_exper)//计算函数
{
int i=0,j=0,k=1;
int br=0;
int temp1,temp2;//临时变量
char dec,CH;
linkstack cha;//定义字符栈
link Num;//定义整数栈
Num.top=0;
cha.top=0;
push1(&cha,'#');
do
{
if (j==0 && C_exper.ch[j]=='(')
{
br++;
}
if (C_exper.ch[j]!='=')
{
if (k==1)
{
push1(&cha,C_exper.ch[j]);
push2(&Num,C_exper.num[i]);
push2(&Num,C_exper.num[++i]);
dec=precede(gettop(&cha),C_exper.ch[++j]);
}
else
{
dec=precede(gettop(&cha),C_exper.ch[j]);
}
}
else
{
temp1=pop2(&Num);
temp2=pop2(&Num);
push2(&Num,operate(temp2,pop1(&cha),temp1));
printf("%d\n\n",pop2(&Num));
break;
}
switch(dec)
{
case '<':
{