Pagini recente » Cod sursa (job #2666636) | Cod sursa (job #868319) | Cod sursa (job #1389986) | Cod sursa (job #788289) | Cod sursa (job #2820535)
#include <bits/stdc++.h>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
int precedence(char ch){
if(ch=='+' || ch=='-'){
return 0;
}
else if(ch=='*' || ch=='/'){
return 1;
}
else{
return -1;
}
}
int operation(int a, int b, char ch){
if(ch=='+'){
return a+b;
}
if(ch=='-'){
return b-a;
}
if(ch=='*'){
return a*b;
}
if(ch=='/'){
return b/a;
}
}
int main(){
string s;
f >> s;
stack<char> op;
string res="";
for(int i=0;i<s.size();++i){
if(s[i]>='0' && s[i]<='9'){
res+=s[i];
int j=i+1;
while(s[j]>='0' && s[j]<='9' && j<s.size()){
res+=s[j];
j++;
}
i=j-1;
res+=' ';
}else{
if(s[i]=='('){
op.push(s[i]);
}else{
if(s[i]==')'){
while(op.top()!='('){
res+=op.top();
res+=' ';
op.pop();
}
op.pop();
}else{
while(!op.empty() && precedence(s[i])<=precedence(op.top())){
res+=op.top();
res+=' ';
op.pop();
}
op.push(s[i]);
}
}
}
}
while(!op.empty()){
res+=op.top();
res+=' ';
op.pop();
}
stack<int> st;
for(int i=0;i<res.size();++i){
if(strchr("+-*/", res[i])){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(operation(a, b, res[i]));
}
else if(res[i]==' '){
}
else{
int j=i;
int nr=0;
while(res[j]!=' ' && j<res.size()){
nr=nr*10+(res[j]-'0');
j++;
}
i=j;
st.push(nr);
}
}
g << st.top();
return 0;
}