您的位置:首页 > 编程语言 > C语言/C++

C++表达式求解

2016-07-01 20:26 363 查看
#include"stack"
#include<string>
using namespace std;

stack<char> Symbol;
stack<double>number;
double Calcul(const string &s);//传表达式进这个函数可以返回运算的值,这里运算只包括加减乘除和括号
void divit()
{
if (!Symbol.empty())
{
if (Symbol.top() == '/')
{
Symbol.pop();
double x = number.top();
number.pop();
divit();
number.push(1.0 / x);
Symbol.push('*');
}
}
}
double Calcul(const string &s)
{
string str=s;

int flag = 0;
for (int i = 0; i < (str.length()); i++)
{
if (str[i] == (wchar_t)'(')
flag++;
if (str[i] == (wchar_t)')')
flag--;
}
if (flag != 0)
{
double result = 0.0;
return result;
}
else
{//100+20*10-55^2
int strat = 0, end = 0;
bool ifstart = false;
for (int i = 0; i < (str.length()); i++)
{
double now = 0.0;//记录数字
double r = 1.0;//基

if (str[i] == '(' || str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/')
{
if (Symbol.empty() == true)
{
Symbol.push(str[i]);
}
else
{
if (str[i] == '+' || str[i] == '-')
{
while (!Symbol.empty())
{
if ((Symbol.top() == '*' || Symbol.top() == '/'))
{
char sym = Symbol.top();
Symbol.pop();
double a = 0.0, b = 0.0;
b = number.top();
number.pop();
if (!Symbol.empty())
{
if (Symbol.top() == '/')
divit();
}
a = number.top();
number.pop();
if (sym == '*')
a = a*b;
if (sym == '/')
a = a / b;
number.push(a);
}
else
break;
}
}
Symbol.push(str[i]);
}
}
else if (str[i] == ')')
{
while (Symbol.top() != '(')
{
char sym = Symbol.top();
Symbol.pop();
double a, b;
a = number.top();
number.pop();
b = number.top();
number.pop();
if (sym == '-')
number.push(b - a);
if (sym == '+')
number.push(b + a);
if (sym == '*')
number.push(b*a);
if (sym == '/')
number.push(b / a);
}
if (Symbol.top() == '(')
Symbol.pop();
}
else if (str[i] >= '0'&&str[i] <= '9' || str[i] == '.')
{
if (ifstart == false)
{
ifstart = true;
strat = i;
}
if (i == str.length() || ((str[i + 1]<'0' || str[i + 1]>'9') && str[i + 1] != '.'))
{
end = i;
ifstart = false;

for (int j = end; j >= strat; j--)
{

if (str[j] == '.')
{
now = now / (r);
r = 1.0;
}
else
{
now += r*(str[j] - '0');
r *= 10.0;
}
}
number.push(now);
}
}

}
}
double result = 0.0;
while (!Symbol.empty())
{
double a, b;
char sym = Symbol.top();
Symbol.pop();
b = number.top();
number.pop();
a = number.top();
number.pop();
if (sym == '+')
{
number.push(a + b);
}
if (sym == '-')
{
number.push(a - b);
}
if (sym == '*')
{
number.push(a * b);
}
if (sym == '/')
{
number.push(a / b);
}
}
result = number.top();
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: