#include<stack>
using std::stack;
//计算运算符的优先级
int pp(wchar_t c)
{
int k=-2;
switch(c){
case '*':case '/':
k=2;
break;
case '+':case '-':
k=1;
break;
case '(':case ')':
k=0;
break;
case '=':
k=-1;
break;
}
return k;
}
//将字符串转换成实数
double shishu(CString *s,int *k)
{
double x,y=1.0;
int flag=1;
x=0.0;
wchar_t c=s->GetAt(*k);
while(c>='0'&&c<='9'||c=='.')
{
*k=*k+1;
if(c>='0'&&c<='9')
if(flag==0)
{
y*=0.1;
x+=(y*(c-48));
}
else
x=10*x+(c-48);
else flag=0;
c=s->GetAt(*k);
}
return x;
}
double GetResult(CString str,CString str1=NULL){
//格式化str
int i=0;
while(0!=str.Replace(L"Ans",str1));
while(str.GetAt(i)==L'-'){
if(i==0)
{
str.Insert(str.Find(L'-'),L'0');
}
else if(str.GetAt(i-1)==L'(')
str.Insert(i,L'0');
}
i=0;
while(str.GetAt(i)!=L'='){
switch(str.GetAt(i))
{
case L'÷':
str.Delete(i);
str.Insert(i,'/');
break;
case L'×':
str.Delete(i);
str.Insert(i,'*');
break;
case L' ':
str.Delete(i);
break;
}
i++;
}
//格式化结束
stack<double>st_data;
stack<wchar_t>st_op;
st_op.push('=');
int flag=1,k;
k=0;
double x,y;
wchar_t c=str.GetAt(k);
while(flag)
{
if(c>=L'0'&&c<=L'9'||c==L'.')
st_data.push(shishu(&str,&k));
else if(c==L'('||pp(c)>pp(st_op.top()))
{
st_op.push(c);
k=k+1;
}
else if((c==L'=')&&(st_op.top()==L'='))
flag=0;
else if((c==L')')&&(st_op.top()==L'('))
{
st_op.pop();
k++;
}
else if(pp(c)<=pp(st_op.top()))
{
y=st_data.top();
st_data.pop();
x=st_data.top();
st_data.pop();
c=st_op.top();
st_op.pop();
switch(c)
{
case L'+':
x=x+y;
break;
case L'-':
x=x-y;
break;
case L'*':
x=x*y;
break;
case L'/':
x=x/y;
break;
}
st_data.push(x);
}
c=str.GetAt(k);
}
return st_data.top();
}