Mai intai trebuie sa te autentifici.
Cod sursa(job #3264955)
| Utilizator | Data | 25 decembrie 2024 23:41:10 | |
|---|---|---|---|
| Problema | Evaluarea unei expresii | Scor | 100 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 1.1 kb |
#include <bits/stdc++.h>
using namespace std;
int n;
string str;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int eval(int &pos);
int factor(int &pos);
int termen(int &pos);
int main() {
getline(fin, str);
n = str.size();
int pos = 0;
fout << eval(pos);
return 0;
}
int eval(int &pos){
int ans = factor(pos);
while(pos < n && (str[pos] == '+' || str[pos] == '-')){
if(str[pos] == '+'){
pos++;
ans += factor(pos);
}else{ // str[pos] == '-'
pos++;
ans -= factor(pos);
}
}
return ans;
}
int factor(int &pos){
int ans = termen(pos);
while(pos < n && (str[pos] == '*' || str[pos] == '/')){
if(str[pos] == '*'){
pos++;
ans *= termen(pos);
}else{ // str[pos] == '/'
pos++;
ans /= termen(pos);
}
}
return ans;
}
int termen(int &pos){
int ans = 0;
if(str[pos] == '('){
pos++;
ans = eval(pos);
pos++;
}else{
while(pos < n && isdigit(str[pos])){
ans *= 10;
ans += (str[pos]-'0');
pos++;
}
}
return ans;
}
