表达式求值

#include<iostream> 
#include<string>
#include<stack>
using namespace std;


class cal
{
public:
cal(){}
cal(string s) :str(s), res(0), IsRight(true){}
void PutStr(string s){ str = s; }
void ShowResult();
private:
int  judge(const char ch1, const char ch2);
float Stof();
void Calculat(); //计算过程
float res; //表达式结果
string str; //表达式字符串
bool  IsRight; //判断表达式书写是否正确
stack<float>Num; //数据栈
stack<char>Opt; //运算符栈
};
void cal::ShowResult()
{
Calculat();


if (IsRight)
cout << res << endl;
else
cout << "表达式有误!" << endl;


}
float cal::Stof()
{
float n = stof(str);


while ((str.front() >= '0' && str.front() <= '9') || str.front() == '.')
{
str.erase(0, 1);
}
return n;
}
int  cal::judge(const char ch1, const char ch2)
{
string tmp = "+-*/()=";
int num[7][7] = { { 1, 1, 0, 0, 0, 1, 1 },
{ 1, 1, 0, 0, 0, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 0, 1, 1 },
{ 0, 0, 0, 0, 0, 2, 4 },
{ 1, 1, 1, 1, 4, 1, 1 },
{ 0, 0, 0, 0, 0, 4, 2 } };
return num[tmp.find(ch1)][tmp.find(ch2)];
}
void cal::Calculat()
{
if (str.empty())
{
IsRight = false;
return;
}
if ('=' != str[str.length() - 1])
str.push_back('=');
Opt.push('=');
while (true)
{
int n = str.find(' ');
if (-1 == n)
break;
str.erase(n, 1);
}


float n1(0), n2(0);
while (!Opt.empty() && !str.empty())
{
if (str.front() >= '0' && str.front() <= '9')
{
Num.push(Stof());
}
else if (str.front() == '+' || str.front() == '-' ||
str.front() == '*' || str.front() == '/' ||
str.front() == '(' || str.front() == ')' ||
str.front() == '=')
{
if (0 == judge(Opt.top(), str.front()))
{
Opt.push(str.front());
str.erase(0, 1);
}
else if (1 == judge(Opt.top(), str.front()))
{
n2 = Num.top();
Num.pop();
n1 = Num.top();
Num.pop();
switch (Opt.top())
{
case '+':n1 += n2;
break;
case '-':n1 -= n2;
break;
case '*':n1 *= n2;
break;
case '/':n1 /= n2;
break;
}
Num.push(n1);
Opt.pop();
}
if (2 == judge(Opt.top(), str.front()))
{
Opt.pop();
str.erase(0, 1);
}


}
else
{
IsRight = false;
return;
}
}
res = Num.top();
}
int main()
{
string str(" 5-4*1-(8+9)*(9-8)");


cal n1(str);
n1.ShowResult();




return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值