Pagini recente » Cod sursa (job #1477443) | Cod sursa (job #2508375) | Cod sursa (job #1927629) | Cod sursa (job #3126811) | Cod sursa (job #3264955)
#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;
}