【问题描述】
设计一个程序,对输入的以#为结束的算术表达式(包括+,-,*,/,(,) ),首先判断表达式是否含有非法字符(即非+,-,*,/, (,) 之外的字符),
如果含有非法字符,则报错误信息;
如果正确,计算并输出这个表示式的值。
本题希望利用算符优先关系,实现对算术四则混合运算表达式的求值。
【输入格式】
以#为结束符的算术表达式。
【输出格式】
对于每组测试数据算术表达式,如果含有非法字符,输出“NO”,否则输出表达式的值,行尾不得有多余的空格。
要求:
使用STL求解表达式的值。
【样例输入】
3+4*(5-3)#
【样例输出】
11
【样例说明】
输入样例是合法的表达式,因此求表达式的值,并输出11。
【样例输入】
3+;4*(5-3)#
【样例输出】
表达式不合法
【样例说明】
输入样例含不合法的字符';',因此输出“NO”。
【特别说明】
建议使用STL
思路:符号存于一个栈中,数字存于另一个栈中,通过分类讨论进行入栈和出栈的操作进行计算
完整代码:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string s;
stack<int> shuzi;
stack<char> fuhao;
cin >> s;
for (int i=0; i<s.size()-1; i++)
{
if (!(s[i]>='0'&&s[i]<='9')&&s[i]!='+'&&s[i]!='-'&&s[i]!='*'&&s[i]!='/'&&s[i]!='('&&s[i]!=')')
{
cout << "NO";
return 0;
}
if (s[i]>='0'&&s[i]<='9')
{
if (i==0||!(s[i-1]>='0'&&s[i-1]<='9'))
{
shuzi.push(s[i]-'0');
continue;
}
else
{
int x1=shuzi.top();
shuzi.pop();
shuzi.push(x1*10+s[i]-'0');
continue;
}
}
if (fuhao.empty())
{
fuhao.push(s[i]);
continue;
}
else
{
if (((s[i]=='+'||s[i]=='-')&&fuhao.top()!='*'&&fuhao.top()!='/')||s[i]=='*'||s[i]=='/'||s[i]=='(')
{
fuhao.push(s[i]);
continue;
}
if ((s[i]=='+'||s[i]=='-')&&(fuhao.top()=='*'||fuhao.top()=='/'))
{
int x2=shuzi.top();
shuzi.pop();
int x1=shuzi.top();
shuzi.pop();
int re=0;
if (fuhao.top()=='*') re=x1*x2;
else re=x1/x2;
shuzi.push(re);
fuhao.pop();
fuhao.push(s[i]);
continue;
}
if (s[i]==')')
{
while(fuhao.top()!='(')
{
int x2=shuzi.top();
shuzi.pop();
int x1=shuzi.top();
shuzi.pop();
int re=0;
if (fuhao.top()=='+') re=x1+x2;
if (fuhao.top()=='-') re=x1-x2;
if (fuhao.top()=='*') re=x1*x2;
if (fuhao.top()=='/') re=x1/x2;
shuzi.push(re);
fuhao.pop();
}
fuhao.pop();
continue;
}
}
}
while(!fuhao.empty())
{
int x2=shuzi.top();
shuzi.pop();
int x1=shuzi.top();
shuzi.pop();
int re=0;
if (fuhao.top()=='*') re=x1*x2;
if (fuhao.top()=='/') re=x1/x2;
if (fuhao.top()=='+')
{
if (fuhao.size()>1)
{
char x=fuhao.top();
fuhao.pop();
if (fuhao.top()!='-') re=x1+x2;
else re=x1-x2;
fuhao.push(x);
}
else re=x1+x2;
}
if (fuhao.top()=='-') re=x1-x2;
fuhao.pop();
shuzi.push(re);
}
cout << shuzi.top();
return 0;
}