# 用栈实现四则运算计算器c#

0

```#include"stdio.h"
#include"string.h"

char stack[200],out[200];
int k=0,t=0;

void up(int a,int b,char flag)
{
int q;
if(flag=='*'){
q=a*b;
out[k]=q+'0';  //当q大于9时存入错误,下面除法一样
k++;
}
else{
q=(a-'0')/(b-'0');
out[k]=q+'0';
k++;
}
}

void result()
{
int len1=strlen(stack)-1,len2=strlen(out)-1;
while(len2>0)
{
if(stack[len1]=='+')out[len2-1]=(out[len2]-'0')+(out[len2-1]-'0')+'0';
else out[len2-1]=(out[len2-1]-'0')-(out[len2]-'0')+'0';
len2-=1;
stack[len1]=NULL;
len1--;
}
printf("%s",out);
}

void translate(char str[])
{
stack[0]='1';
char ch,flag;
int i=0,l=0,j=0;
int a,b;

ch=str[i];

while(ch!='\0')
{
switch(ch){
case '-':
case '+':
for(l;l<strlen(stack);l++)
if(stack[l]=='*'||stack[l]=='/')break;
flag=stack[l];
stack[l]=ch;
k=k-2;
a=out[k]-'0';b=out[k+1]-'0';
out[k]=NULL;

up(a,b,flag);
break;
case '*':
case '/':
stack[t]=ch;t++;
break;
default:
j=0;
while(ch>='0'&&ch<='9'){
j=j*10+(ch-'0');
i++;
ch=str[i];
}
i--;
out[k]=j+'0';k++;
break;
}
i++;
ch=str[i];
}
}

int main()
{
FILE *fp;
char str[200];
gets(str);
fputs(str,fp);
translate(str);
result();
fputc('=',fp);
fputs(out,fp);
fclose(fp);
}```

char a[2];

int a =45;

0

0

您需要登录以后才能回答，未注册用户请先注册