#include
#include
#include
#include
#include
using namespace std;
const char Tab=0x9;
const int DIGIT=1;
double fun(double x,char op[],int *iop)
{
while(op[*iop-1]<32)
switch(op[*iop-1])
{
case 7: x=sin(x); (*iop)--;break;
case 8: x=cos(x); (*iop)--;break;
case 9: x=tan(x); (*iop)--;break;
case 10: x=sqrt(x); (*iop)--;break;
case 11: x=asin(x); (*iop)--;break;
case 12: x=acos(x); (*iop)--;break;
case 13: x=atan(x); (*iop)--;break;
case 14: x=log10(x);(*iop)--;break;
case 15: x=log(x); (*iop)--;break;
case 16: x=exp(x); (*iop)--;break;
}
return x;
}
double calc(char *expr,char **addr)
{
static deep;
static char *fname[]={ "sin","cos","tan","sqrt","arcsin","arccos","arctan","lg","ln","exp",NULL};
double ST[10]={0.0};
char op[10]={'+'};
char c,*rexp,*pp,*pf;
int ist=1,iop=1,last;
if(!deep)
{
pp=pf=expr;
do
{
c = *pp++;
if(c!=' '&& c!=Tab)
*pf++ = c;
}
while(c!='\0');
}
pp=expr;
if((c=*pp)=='-'||c=='+')
{
op[0] = c;
pp++;
}
last = !DIGIT;
while((c=*pp)!='\0')
{
if(c=='(')
{
deep++;
ST[ist++]=calc(++pp,addr);
deep--;
ST[ist-1]=fun(ST[ist-1],op,&iop);
pp = *addr;
last = DIGIT;
if(*pp == '('||isalpha(*pp) && strnicmp(pp,"Pi",2))
{
op[iop++]='*';
last = !DIGIT;
c = op[--iop];
goto operate ;
}
}
else if(c==')')
{
pp++;
break;
}
else if(isalpha(c))
{
if(!strnicmp(pp,"Pi",2))
{
if(last==DIGIT){cout<< "π左侧遇)" <
ST[ist-1]=fun(ST[ist-1],op,&iop);
pp += 2;
last = DIGIT;
if(!strnicmp(pp,"Pi",2)){cout<< "两个π相连" <
else
{
for(int i=0; (pf=fname[i])!=NULL; i++)
if(!strnicmp(pp,pf,strlen(pf)))break;
if(pf!=NULL)
{
op[iop++] = 07+i;
pp += strlen(pf);
}
else {cout<< "陌生函数名" <
}
else if(c=='+'||c=='-'||c=='*'||c=='/'||c=='^')
{
char cc;
if(last != DIGIT){cout<< "运算符粘连" <
if(c=='+'||c=='-')
{
do
{
cc = op[--iop];
--ist;
switch(cc)
{
case '+': ST[ist-1] += ST[ist];break;
case '-': ST[ist-1] -= ST[ist];break;
case '*': ST[ist-1] *= ST[ist];break;
case '/': ST[ist-1] /= ST[ist];break;
case '^': ST[ist-1] = pow(ST[ist-1],ST[ist]);break;
}
}
while(iop);
op[iop++] = c;
}
else if(c=='*'||c=='/')
{
operate: cc = op[iop-1];
if(cc=='+'||cc=='-')
{
op[iop++] = c;
}
else
{
--ist;
op[iop-1] = c;
switch(cc)
{
case '*': ST[ist-1] *= ST[ist];break;
case '/': ST[ist-1] /= ST[ist];break;
case '^': ST[ist-1] = pow(ST[ist-1],ST[ist]);break;
}
}
}
else
{
cc = op[iop-1];
if(cc=='^'){cout<< "乘幂符连用" <
}
last = !DIGIT;
}
else
{
if(last == DIGIT){cout<< "两数字粘连" <
ST[ist-1]=fun(ST[ist-1],op,&iop);
if(pp == rexp){cout<< "非法字符" <
pp = rexp;
last = DIGIT;
if(*pp == '('||isalpha(*pp))
{
op[iop++]='*';
last = !DIGIT;
c = op[--iop];
goto operate ;
}
}
}
*addr=pp;
if(iop>=ist){cout<< "表达式有误" <
{
--ist;
switch(op[--iop])
{
case '+': ST[ist-1] += ST[ist];break;
case '-': ST[ist-1] -= ST[ist];break;
case '*': ST[ist-1] *= ST[ist];break;
case '/': ST[ist-1] /= ST[ist];break;
case '^': ST[ist-1] = pow(ST[ist-1],ST[ist]);break;
}
}
return ST[0];
}
int main()
{
char s[128],*end;
while(1)
{
cout << "请输入表达式:";
cin.getline(s,128);
cout << setprecision(17) << calc(s,&end) << endl;
}
return 0;
}