#include <stdlib.h>
#include "math.h"
char* getn(char *c)
{
int dot = 0;
if (c == 0)return c;
while(*c)
{
if (*c >= '0' && *c <='9'){}
else if (*c == '.'){dot++;if (dot>2){return 0;}}
else break;
c++;
}
return c;
}
char* skip(char *c, int *dep)
{
while(*c)
{
if (*c == ' ' || *c == '\t'){}
else if (*c == '(')(*dep)++;
else if (*c == ')'){if (*dep>0)(*dep)--;else return 0;}
else break;
c++;
}
return c;
}
typedef enum
{
ADD,SUB,MUL,DIV,SIN,COS,SQR,LST
}OP;
char *name[]=
{"+","-","*","/","sin","cos","sqrt"};
char* mark(OP m)
{
if (m <LST)return name[m];
return 0;
}
OP oper(char* c)
{
OP m;
for (m=0;m<LST;m++){
if (strncmp(c,name[m],strlen(name[m]))==0){
return m;
}
}
return LST;
}
int calc(char* exp)
{
double op[100];
double res = 0;
int n = 0;
int m = 0;
int opr[100];
char *pos = exp;
char *nxt;
int dep = 0;
while (1)
{
OP p;
pos = skip(pos,&dep);
if (pos == 0 || *pos == 0)break;
if ((p = oper(pos)) < LST)
{
if (n >= 100) return -2;
if (p < SIN){
if (m < 1)return -2;
opr[n++] = p + (dep<<8) + ((m-1)<<16);
}
else opr[n++] = p + (dep<<8) + (m<<16);
pos += strlen(name[p]);
}
else if (*pos >= '0' && *pos <='9')
{
nxt = getn(pos);
if (m >= 100)return -2;
op[m++] = atof(pos);
pos = nxt;
}
else return -3;
}
if (dep != 0)return -5;
printf("Total:%d %d\n",m,n);
while (n > 0)
{
int b = opr[0];
OP p;
int i = 0, j = 0;
for (i=1;i<n;i++){if ((opr[i]&0xFFFF) >= (b & 0xFFFF)){b=opr[i];j=i;}}
i = b>>16;
p = (OP)b & 0xFF;
if (p < SIN)
{
int k;
if (i+1 < m)printf("%f%s%f\n",op[i],mark(p),op[i+1]);
else return -6;
}
else
{
printf("%s(%f)\n",mark(p),op[i]);
}
switch(p)
{
case ADD:op[i]= op[i]+op[i+1];break;
case SUB:op[i]= op[i]-op[i+1];break;
case MUL:op[i]= op[i]*op[i+1];break;
case DIV:if (op[i+1] != 0)op[i]= op[i]/op[i+1];
else return -4;
break;
case SIN:op[i]=sin(op[i]);break;
case COS:op[i]=cos(op[i]);break;
case SQR:op[i]=sqrt(op[i]);break;
}
if (p < SIN){
for (;i<m-1;i++){op[i+1] = op[i+2];}m--;}
for (i=j;i<n;i++){
if (p < SIN)opr[i+1] = (opr[i+1]& 0xFFFF) + (((opr[i+1]>>16)-1)<<16);
opr[i]=opr[i+1];
}
n--;
}
printf("\n%s=%f\n", exp, op[0]);
return 0;
}
int main()
{
calc("sin(1.57+1.57*(2-2)*3*8))");
calc("1");
calc("2*cos(sin(1+2)+1)");
calc("1+2*3-4/6");
calc("(1+2)*3*4-1+sqrt(3+2*3)");
getch();
return 0;
}
温馨提示:答案为网友推荐,仅供参考