算数四则运算的规则是
1.先乘除,后加减;
2.从左算到右;
3.先括号内,后括号外。
由此,算式4+2*3-10/5的计算顺序为4+2*3-10/5=4+6-10/5=4+6-2=8。
给定一个以“#”作为结束符的算式,求出算式的结果。
给出严蔚敏《数据结构(C语言)》中的一段算法描述以作参考:
下面是一个总结出来用栈来求表达式值的一个口诀:
Input Description
以“#”结尾的表达式,运算数为正整数。每个表达式占一行。
Output Description
输出表达式运算的结果。
Sample Input
4+2*3-10/5#
3*(7-2)#
2*3/2#
Sample Output
8
15
3
#include<iostream>
using namespace std;
#include<stack>
#include<algorithm>
#include<string>
stack<int>num;
stack<char>opera;
void work()
{
char op = opera.top();//操作符出栈
int b = num.top();//操作数1出栈
num.pop();
int a = num.top();//操作数2出栈
//注意操作数先出栈的为右操作数
num.pop();
int tmp;
if (op == '+')
{
tmp = a + b;
}
else if (op == '-')
{
tmp = a - b;
}
else if (op == '*')
{
tmp = a * b;
}
else if (op == '/')
{
tmp = a / b;
}
num.push(tmp);//得到的数据进行入栈
opera.pop();
}
int bigger(char c)
{
if (c == '+' || c == '-')
{
return 0;
}
else if (c == '*' || c == '/')
{
return 1;
}
}
int main()
{
string a;
while (cin >> a)
{
while (!num.empty())//数字栈不空全部出栈
{
num.pop();
}
while (!opera.empty())//操作符栈不空全部出栈
{
opera.pop();
}
int len = a.size();//a的长度
for (int i = 0; i < len; i++)
{
if (a[i] >= '0' && a[i] <= '9')//若为数字123 要将字符'1', '2', '3'转化为整数123
{
int tmp = 0;
while (a[i] >= '0' && a[i] <= '9')
{
tmp = tmp * 10 + (a[i] - '0');
i++;
}
num.push(tmp);//转化后的整数入栈
i--;
}
else if (a[i] == '#')//如果为等号直接结束 代表表达式结束了
{
break;
}
else
{
if (opera.empty() || opera.top() == '(')//栈为空 或者栈顶为左括号就直接入栈
{
opera.push(a[i]);
}
else if (a[i] == ')')//此时为右括号就全部出栈 直到碰见左括号
{
while (opera.top() != '(')
{
work();
}
opera.pop();
}
else//栈顶不为右括号的时候
{
//只有当栈顶元素符号的优先级大于扫描元素的优先级才出栈(扫描元素的优先级小于等于栈顶元素)
while (!opera.empty() && opera.top() != '(' && bigger(a[i]) <= bigger(opera.top()))
{
work();
}
opera.push(a[i]);//扫描元素入栈
}
}
}
while (!opera.empty())
{
work();
}
cout << num.top() << endl;
}
return 0;
}