算术表达式求值
题目内容:
输入一个由数字、+,-,*,/ 组成的算术表达式,求其值。
输入描述
一个表达式,其中每个运算数为正整数
输出描述
计算结果,保留2位小数
输入样例
1+12*3-4/2
输出样例
35.00
这里先将中缀转为后缀, 没有括号的情况比较简单, 转换规则为
1. 设置两个stack, num和ope
2. 遍历表达式串
3. 遇到数字直接入num
4. 遇到操作符有两种情况
==1. ope为空直接入ope栈
==2. ope不为空则与 ope.top() (设其为top)进行比较
=====a. 若top优先级更低则直接入ope栈
=====b. top优先级更高, 则取num两个数字与top运算, 结果入num栈,继续与新的ope.top()比较, 若把ope比较空了则操作符直接入栈
5. 遍历完了后, ope不为空的话重复取num两个数字与ope.top()运算, 结果入num栈, 直至ope空
代码如下
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<memory.h>
#include<queue>
#include<cmath>
#include<iomanip>
#include<stack>
using namespace std;
string str;
stack<double> n;
stack<char> o;
bool is_num(char a)
{
if(a <= '9' && a >= '0') return true;
return false;
}
int get(char c)
{
if(c == '*' || c == '/') return 2;
return 1;
}
double cal(double a, char c, double b)
{
if(c == '+') return a + b;
if(c == '-') return a - b;
if(c == '*') return a * b;
return a / b;
}
double solve()
{
int len = str.length();
for(int i = 0; i < len; i++)
{
if(is_num(str[i])) //遇到数字字符要取出完整数字来
{
int temp = 0;
while(i < len && is_num(str[i]))
temp = temp * 10 + str[i++] - '0';
i--;
n.push(temp);
}
else
{
if(o.empty()) //ope is empty
o.push(str[i]);
else
{
while(!o.empty() && get(o.top()) > get(str[i]))
{
double num1 = n.top();
n.pop();
double num2 = n.top();
n.pop();
n.push(cal(num2, o.top(), num1));
o.pop();
}
o.push(str[i]);
}
}
}
while(!o.empty())
{
double num1 = n.top();
n.pop();
double num2 = n.top();
n.pop();
n.push(cal(num2, o.top(), num1));
o.pop();
}
return n.top();
}
int main()
{
ios::sync_with_stdio(false);
cin >> str;
cout<<setiosflags(ios::fixed)<<setprecision(2)<<solve();
}
c++中设置输出的函数在头文件 中, setprecision(x) 设置有效数字为x位, setiosflags(ios::fixed)将浮点数以固定小数点位数显示, 两个合起来实现固定小数点后有效位