表达式求值是进行数据处理的最基本操作。请编写程序完成一个简单算术表达式的求值。要求如下:
(1) 运算符包括:+、-、*、-、^(乘方)、括号
(2)运算量为数值常量,根据自己的能力可以对运算量做不同的约束,例如1位整数、多位整数、实数等(会有不同的测试用例);
输入:一行,即表达式,以“=”结束。例如:
5*(8-3)+6/5=
输出:一行,即表达式的值。结果值为整数时输出为整数,如果有小数时保留5位小数。
26.20000
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
stack<char>op;
stack<double>num;
string s;
bool isop(char c){
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '=' || c == '(' || c == ')') return 1;
return 0;
}
int level(char c){
if (c == '=') return 0;
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
if (c == '^') return 3;
if (c == '(' || c == ')') return 4;
return -1;
}
double tonum(int l,int r){
double res = 0,div=1;
for (int i=l;i<=r;++i){
if (s[i] == '.'){
div = pow(10,r-i);
}
else res = res * 10 + s[i] - '0';
}
return res / div;
}
double solve(double x,double y,char c){
if (c == '+') return x + y;
if (c == '-') return x - y;
if (c == '*') return x * y;
if (c == '/') return x / y;
if (c == '^') return pow(x,y);
return 0;
}
void calc(){
char opp = op.top(); op.pop();
double y = num.top(); num.pop();
double x = num.top(); num.pop();
double z = solve(x,y,opp);
num.push(z);
}
void done(char c){
int l1 = level(op.top()), l2 = level(c);
if (l1 < l2){
if (c == ')'){
calc();
done(c);
}
else op.push(c);
}
else if (l1 == l2 && (op.top() == '=' || ( op.top() == '(' && c == ')'))) op.pop();
else {
if (!op.empty()){
if (op.top() == '(') op.push(c);
else {
calc();
done(c);
}
}
else return ;
}
}
int main (){
cin>>s;
int n = s.size(),l=-1,r=-1;
op.push('=');
for (int i=0;i<n;++i){
if (!isop(s[i])){
if (l == -1) l = r = i;
else r = i;
}
else {
if (l != -1) {
double tmp = tonum(l,r);
num.push(tmp);
l = r = -1;
}
done(s[i]);
}
}
double ans = num.top();
if (ans == (ll)ans) printf("%lld\n",(ll)ans);
else printf("%.5f\n",ans);
return 0;
}