Pagini recente » Cod sursa (job #3143001) | Cod sursa (job #2266993) | Cod sursa (job #1376778) | Cod sursa (job #892621) | Cod sursa (job #2976256)
#include <fstream>
#include <cctype>
#include <cstring>
#include <stack>
using namespace std;
ifstream fin ("evaluare.in");
ofstream fout ("evaluare.out");
const int NMAX=100001;
char s[NMAX];
stack<int>polo;
stack<char>op;
int calcul (int a, int b, char ch)
{
switch (ch)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
}
int prior (char ch)
{
switch(ch)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
}
return 0;
}
int main()
{
int n,i,x,a,b,c;
char ch;
fin.getline(s,NMAX);
n=strlen(s);
x=0;
i=0;
while (i<n)
{
if (isdigit(s[i]))
{
x=x*10+s[i]-'0';
i++;
while(i<n && isdigit(s[i]))
{
x=x*10+s[i]-'0';
i++;
}
polo.push(x);
x=0;
continue;
}
if (s[i]=='(')
{
op.push('(');
i++;
continue;
}
if (s[i]=='+' || s[i]=='-' || s[i]=='/' || s[i]=='*')
{
if (op.empty() || op.top()=='(' || prior(op.top())<prior(s[i]))
op.push(s[i]);
else
{
while (!op.empty() && prior(op.top())>=prior(s[i]))
{
ch=op.top();
op.pop();
b=polo.top();
polo.pop();
a=polo.top();
polo.top()=calcul(a,b,ch);
}
op.push(s[i]);
}
i++;
continue;
}
if (s[i]==')')
{
while (!op.empty() && op.top()!='(')
{
ch=op.top();
op.pop();
b=polo.top();
polo.pop();
a=polo.top();
polo.top()=calcul(a,b,ch);
}
op.pop();
i++;
continue;
}
}
while (!op.empty())
{
ch=op.top();
op.pop();
b=polo.top();
polo.pop();
a=polo.top();
polo.top()=calcul(a,b,ch);
}
fout<<polo.top();
return 0;
}