nguyenvanhieu2132004
Rating
-
Bài tập
0
Điểm
0
Rating #
-
Điểm #
28176
Giới thiệu
include <iostream>
include <vector>
include <stack>
include <map>
include<iomanip>
include<cmath>
using namespace std;
class Leksema {
public:
char type;
double value;
Leksema(char t, double v) : type(t), value(v) {}
};
double calculate(double a, double b, char op) {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: return 0;
}
}
double stackAnalyze(const vector<Leksema>& list) {
stack<double> nStack;
stack<char> oStack;
map<char, int> priority;
priority['+'] = 1;
priority['-'] = 1;
priority['*'] = 2;
priority['/'] = 2;
priority['('] = 0;
for(size_t i = 0; i < list.size(); ) {
switch (list[i].type) {
case 'n':
nStack.push(list[i].value);
i++;
break;
case '(':
oStack.push(list[i].type);
i++;
break;
case ')':
if(oStack.top() != '(') {
double b = nStack.top();
nStack.pop();
double a = nStack.top();
nStack.pop();
nStack.push(calculate(a, b, oStack.top()));
oStack.pop();
} else {
oStack.pop();
i++;
}
break;
default:
if(oStack.empty() || priority[oStack.top()] < priority[list[i].type]) {
oStack.push(list[i].type);
i++;
} else if(oStack.top() != '(') {
double b = nStack.top();
nStack.pop();
double a = nStack.top();
nStack.pop();
nStack.push(calculate(a, b, oStack.top()));
oStack.pop();
}
}
}
while(!oStack.empty()) {
double b = nStack.top();
nStack.pop();
double a = nStack.top();
nStack.pop();
nStack.push(calculate(a, b, oStack.top()));
oStack.pop();
}
return nStack.top();
}
vector<Leksema> lexAnalyze(const string& s) {
vector<Leksema> list;
size_t i = 0;
while(i < s.length()) {
char symb = s[i];
if(symb == '+' || symb == '-' || symb == '*' || symb == '/' || symb == '(' || symb == ')') {
list.push_back(Leksema(symb, 0));
i++;
} else {
if(s[i] >= '0' && s[i] <= '9') {
string num;
do {
num += s[i];
i++;
if(i == s.length()) {
break;
}
} while(s[i] >= '0' && s[i] <= '9' || s[i] == '.');
list.push_back(Leksema('n', stod(num)));
} else {
i++;
}
}
}
return list;
}
bool check(string s){
for(int i=0;i<s.size();i++){
if(s[i]=='.') return 1;
}
return 0;
}
int main() {
string expression;
getline(cin, expression);
vector<Leksema> list = lexAnalyze(expression);
double ans = stackAnalyze(list);
if(floor(ans)==ans&&check(expression)){
cout<<ans<<".0"<<endl;
}
else if(floor(ans)==ans) {
cout <<static_cast<int>(ans)<<endl;
}
else cout<<round(ans * 10.0) / 10.0 <<endl;
return 0;
}