#include<iostream>
using namespace std;
#include<string>
class Expression
{
private:
string str;
int Compare(char str1, char str2);
public:
Expression(string str3);
~Expression();
double& Compute();
};
Expression::Expression(string str3) :str(str3 + '#') {}
Expression::~Expression() {}
int Expression::Compare(char str1, char str2)
{
switch (str1)
{
case '+': case'-':
if (str2 == '(' || str2 == '#')
{
return 1;
}
else
{
return -1;
}
break;
case '*': case '/':
if (str2 == '*' || str2 == '/')
{
return -1;
}
else
{
return 1;
}
break;
case '(':
return 1;
break;
case ')':
if (str2 == '(')
{
return 0;
}
else
{
return -1;
}
break;
case '#':
if (str2 == '#')
{
return 0;
}
else
{
return -1;
}
break;
default:
break;
}
}
double& Expression::Compute()
{
double OPND[100];
char OPTR[100];
OPTR[0] = '#';
int top_nd = -1, top_tr = 0;
double x = 0.0, y = 0.0, z = 0.0;
int i = 0, k = 0;
char op;
for (i = 0; i < this->str.size();)
{
if (this->str[i] >= '0' && this->str[i] <= '9')
{
double value = 0;
while (this->str[i] >= '0' && this->str[i] <= '9')
{
value = (10 * value + str[i]) - '0';
i++;
}
if (this->str[i] == '.')
{
int r = 10;
i++;
while (this->str[i] >= '0' && this->str[i] <= '9')
{
value += static_cast<double>(this->str[i] - '0') / r;
r = 10 * r;
i++;
}
}
OPND[++top_nd] = value;
}
else
{
k = this->Compare(this->str[i], OPTR[top_tr]);
if (k == 1)
{
OPTR[++top_tr] = this->str[i++];
}
else if (k == -1)
{
y = OPND[top_nd--];
x = OPND[top_nd--];
op = OPTR[top_tr--];
switch (op)
{
case '+':
z = x + y;
break;
case '-':
z = x - y;
break;
case '*':
z = x * y;
break;
case '/':
z = x / y;
break;
default:
break;
}
OPND[++top_nd] = z;
}
else
{
top_tr--;
i++;
}
}
}
return OPND[top_nd];
}
int main()
{
cout << "******************************" << endl
<< "程序功能:表达式求值 " << endl
<< "******************************" << endl;
string str;
cout << "请输入一个表达式:" << endl;
cin >> str;
Expression E(str);
double result = E.Compute();
cout << "表达式的值为:" << result << endl;
system("pause");
return 0;
}