Pagini recente » Cod sursa (job #1661378) | Cod sursa (job #2137529) | Cod sursa (job #2181998) | Cod sursa (job #1426097) | Cod sursa (job #2988947)
#include <iostream>
#include <fstream>
#include <stack>
#include <cstring>
using namespace std;
ifstream f ("evaluare.in");
ofstream g ("evaluare.out");
stack<int>numere;
stack<char>op;
char sir[100001];
int l;
int eval(int nr1,int nr2,char op)
{
if(op=='+')
return nr1+nr2;
if(op=='*')
return nr1*nr2;
if(op=='-')
return nr2-nr1;
if(op=='/')
return nr2/nr1;
}
int putere(char op)
{
if(op=='+'||op=='-')
return 1;
if(op=='*' || op=='/')
return 2;
return 0;
}
int main()
{
f >> sir;
l = strlen(sir);
for(int i = 0; i<l; i++)
{
if(sir[i]=='(')
{
op.push(sir[i]);
continue;
}
if(isdigit(sir[i]))
{
int nr = 0;
while(isdigit(sir[i]))
{
nr = nr*10+sir[i]-'0';
i++;
}
i--;
numere.push(nr);
continue;
}
if(sir[i]==')')
{
while(!op.empty() && op.top()!='(')
{
int nr1 = numere.top();
numere.pop();
int nr2 = numere.top();
numere.pop();
char semn = op.top();
op.pop();
int nrnou = eval(nr1,nr2,semn);
numere.push(nrnou);
}
op.pop();
continue;
}
while(!op.empty() && putere(sir[i])<=putere(op.top()))
{
while(!op.empty() && op.top()!='(')
{
int nr1 = numere.top();
numere.pop();
int nr2 = numere.top();
numere.pop();
char semn = op.top();
op.pop();
int nrnou = eval(nr1,nr2,semn);
numere.push(nrnou);
}
}
op.push(sir[i]);
}
while(!op.empty())
{
int nr1 = numere.top();
numere.pop();
int nr2 = numere.top();
numere.pop();
char semn = op.top();
op.pop();
int nrnou = eval(nr1,nr2,semn);
numere.push(nrnou);
}
g << numere.top();
}