数据结构与算法实验4(栈应用)中缀表达式计算
栈ADT应用:中缀表达式求值
表达式求值是进行数据处理的最基本操作。请编写程序完成一个简单算术表达式的求值。要求如下:
(1) 运算符包括:+、-、*、-、^(乘方)、括号
(2)运算量为数值常量,根据自己的能力可以对运算量做不同的约束,例如1位整数、多位整数、实数等(会有不同的测试用例);
输入:一行,即表达式,以“=”结束。例如:
5*(8-3)+6/5=
输出:一行,即表达式的值。结果值为整数时输出为整数,如果有小数时保留5位小数。
26.20000
例如:
输入 | Result |
---|---|
|
|
ps:训练赛做过。大致思路就是把遇到左括号进栈,遇到右括号一直弹出运算符计算,一直到左括号,break。弹出左括号。遇到数字计算(注意可能是浮点数)。遇到运算符,如果括号里面的运算级比当前高,则计算一下。最后把当前运算符入栈。注意计算的时候,弹出的先是后面的b。
下面是代码。
#pragma comment(linker, "/STACK:1024000000,1024000000")
#pragma GCC optimize(3,"Ofast","inline")
#include <bits/stdc++.h>
using namespace std;
#define rep(i , a , b) for(register int i=(a);i<=(b);i++)
#define per(i , a , b) for(register int i=(a);i>=(b);i--)
#define ms(s) memset(s, 0, sizeof(s))
#define squ(x) (x)*(x)
#define fi first
#define se second
template<class T>
inline void read (T &x) {
x = 0;
int sign = 1;
char c = getchar ();
while (c < '0' || c > '9') {
if ( c == '-' ) sign = - 1;
c = getchar ();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar ();
}
x = x * sign;
}
const int maxn = 2e5 + 10;
char s[maxn];
stack<double>p;
stack<char>op;
int opl(char x) {
if(x=='+'||x=='-') return 1;
if(x=='/'||x=='*') return 2;
if(x=='^') return 3;
return 0;
}
void cal() {
double b =p.top();
p.pop();
double a =p.top();
p.pop();
double x=op.top();
op.pop();
if(x=='+') p.push(a+b);
if(x=='-') p.push(a-b);
if(x=='*') p.push(a*b);
if(x=='/') p.push(a/b);
if(x=='^') p.push(pow(a,b));
}
int main(int argc, char * argv[])
{
scanf("%s",s+1);
int n = strlen(s+1);
double tmp = 0,tmp1=0;
int f=0,f1=0;
rep(i,1,n-1) {
if(s[i]>='0'&&s[i]<='9') {
if(f1==0) {
tmp=tmp*10+s[i]-'0';
f=1;
}
else {
tmp1=tmp1+(s[i]-'0')*1.0/pow(10,f1);
f1++;
}
continue;
}
if(s[i]=='.') {
f1=1;
continue;
}
if(f) {
tmp=tmp+tmp1;
p.push(tmp);
tmp=0;
tmp1=0;
f=0;
f1=0;
}
if(s[i]=='(') {
op.push(s[i]);
continue;
}
if(s[i]==')') {
while(op.top()!='(') {
cal();
}
op.pop();
continue;
}
while(op.size()&&opl(op.top())>=opl(s[i])) {
cal();
}
op.push(s[i]);
}
if(f) {
tmp=tmp+tmp1;
p.push(tmp);
tmp=0;
tmp1=0;
f=0;
f1=0;
}
while(op.size()) {
cal();
}
bool is_f = int(p.top())-p.top()==0?0:1;
if(is_f) printf("%.5f\n",p.top());
else printf("%.0f\n",p.top());
return 0;
}