四则运算

#include "stdio.h"
#include<stdlib.h>
#include<string.h>
char s[100];

struct my
{
char *s;
int v;
};
void f2(char *s, int f, int f4);
int f1(char *p);
struct my *ff(char *p, int f);
void main( )
{

int i; int f;
char *p;
p=s;
gets(s);

while((f=f1(s))!=-1) 
{
f2(s,f,1);
}

}
struct my *ff(char *p, int f)
{

char s1[100];
struct my *r;
char *s;
int i=0, j=1, k=0;
s=p;strcpy(s1,s); r=malloc(sizeof(struct my));
if(f==0)
{
p--;
while(*p>='0'&&*p<='9')
{
i+=(*p-'0')*j;
j=j*10;
p--;
}
p++;
r->v=i; r->s=p;
return r;
}
if(f==1)
{
p++;
while(*p>='0'&&*p<='9') {p++; k++;}
p=s;
p++;
for(f=0; f<k-1; f++) j*=10;
while(*p>='0'&&*p<='9')
{
i+=(*p-'0')*j;
j=j/10;
p++;
}
r->v=i; r->s=p;
return r;
}

}

int f1(char *p)  // 确定 运算顺序..
{
int f1=0, f2=0, f3=0;
while(*p!=0)
{
if(*p=='+'||*p=='-')   f1=1;
if(*p=='*'||*p=='/')   f2=1;
if(*p=='(')     f3=1;
*p++;
}
if(f3) return 2;
if(f2) return 1;
if(f1) return 0;
else return -1;
}

void f2(char *s , int f, int f4)
{char s1[100];
char *q, *w, *p=s, *p1=s1;
char e[100] , e1[100];

char *z1, *z2, *z3; int f3;
strcpy(s1,s);
switch(f)
{
case 0:
while(*p!='+'&&*p!='-') {p1++; p++;}
q=ff(p, 0)->s; w=ff(p1,1)->s;
if(*p=='+')
itoa(ff(p,0)->v+ff(p,1)->v, e, 10);
else
itoa(ff(p,0)->v-ff(p,1)->v, e, 10);
break;

case 1:
while(*p!='*'&&*p!='/') {p1++; p++;}
q=ff(p, 0)->s; w=ff(p1,1)->s;
if(*p=='*')
itoa(ff(p,0)->v*ff(p,1)->v, e, 10);
else
itoa(ff(p,0)->v/ff(p,1)->v, e, 10);
break;

case 2:
while(*p!=')')
{ if(*p=='(')  z1=p;  p++; p1++;}
z2=p;  z3=p1;
*z2='';
strcpy(e, z1+1);
strcpy(e1, e);
while((f3=f1(e))!=-1) 
{
f2(e,f3,0);
}
strcpy(z1, e);
strcat(s,z3+1); puts(s); 
break;

}
if(f<=1)
{
strcpy(q,e);
strcat(s,w);
strcpy(s1,s);
if(f4) puts(s);
}
}

原文地址:https://www.cnblogs.com/fitfit/p/4381360.html