Pagini recente » Cod sursa (job #1099034) | Cod sursa (job #3148870) | Cod sursa (job #955272) | Cod sursa (job #883628) | Cod sursa (job #2210961)
#include<bits/stdc++.h>
using namespace std;
const int nmax=1500000000;
string ex;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int i;
int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
string rev(string s)
{
string s1;
for (int i=s.size()-1;i>=0;i--)
if (s[i]=='(') s1=s1+')'; else
if (s[i]==')') s1=s1+'(';
else s1=s1+s[i];
return s1;
}
void itp(string s)
{
stack<int> st;
st.push('N');
int l = s.length();
string ns;
for(int i = 0; i < l; i++)
{
if (s[i]>='0' && s[i]<='9')
{
while (s[i]>='0' && s[i]<='9')
{
ns+=s[i];
i++;
}
ns+=' ';
i--;
}
else if (s[i]=='(')
st.push('(');
else if (s[i]==')')
{
while(st.top() != '(' && st.top() != 'N')
{
char c = st.top();
st.pop();
ns += c;
}
if (st.top()=='(') st.pop();
}
else {
while(st.top() != 'N' && prec(s[i])<=prec( st.top() ) )
{
char c = st.top();
st.pop();
ns += c;
}
st.push(s[i]);
}
}
while(st.top() != 'N')
{
char c = st.top();
st.pop();
ns += c;
}
ex=ns;
}
int val(int a,int b,char c)
{
if (c=='+') return a+b;
if (c=='-') return a-b;
if (c=='/') return a/b;
if (c=='*') return a*b;
}
void eval(string s)
{
stack<int> ns;
stack<char> ss;
bool po=0;
int l=s.size();
int o2,o1=nmax;
for (i=0;i<l;i++)
{
if (s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/')
{
o1=ns.top();
ns.pop();
o2=ns.top();
ns.pop();
ns.push(val(o2,o1,s[i]));
}
else if (s[i]>='0' && s[i]<='9')
{
int o=0;
while (s[i]>='0' && s[i]<='9')
{o=o*10+s[i]-'0'; i++;} i--;
ns.push(o);
}
}
fout<<ns.top();
}
int main()
{
fin>>ex;
//ex=rev(ex);
itp(ex);
//ex=rev(ex);
//fout<<ex;
eval(ex);
return 0;
}