Pagini recente » Cod sursa (job #2556587) | Cod sursa (job #2156411) | Cod sursa (job #1406818) | Cod sursa (job #2214071) | Cod sursa (job #2088776)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const string Functii[] = {"abs", "cos", "sin", "tan"};
const char Operatii[] = {'+', '-', '*', '/'};
const int nrfunctii = 4, nroperatii=4;
struct nod {
double val = 0;
string sp = "";
nod* op1;
nod* op2;
};
nod* Evaluare(string exp);
void ScrieReguli();
double GetValue(nod* act);
int main()
{
string exp;
//ScrieReguli();
//cout << "Introduce-ti expresia: ";
cin >> exp;
nod* start = Evaluare(exp);
cout << GetValue(start) << '\n';
return 0;
}
void ScrieReguli()
{
char line[200];
ifstream fin("reguli.txt");
while (fin.getline(line, 200))
cout << line << '\n';
}
int SearchFunction(string exp, int s, int d)
{
for (int i = 0; i < nrfunctii; i++)
if (exp.find(Functii[i]))
return exp.find(Functii[i]);
}
double StrToDouble(string exp)
{
double x=0;
if (exp.find('.') != string::npos)
{
double y=0;
for (int i = 0; i < exp.find('.'); i++)
x = x * 10 + exp[i] - '0';
for (int i = exp.size()-1; i > exp.find('.'); i--)
y = y / 10 + exp[i] - '0';
return x + y/10;
}
for (int i = 0; i < exp.size(); i++)
x = x * 10 + exp[i] - '0';
return x;
}
bool FirstAndLastPar(string exp)
{
int P[1000], last = 0;;
for (int i = 0; i < exp.size()-1; i++)
if (exp[i] == '(')
P[last++] = i;
else if (exp[i] == ')')
last--;
if (exp[exp.size() - 1] == ')' && P[0] == 0)
return 1;
return 0;
}
nod* Evaluare(string exp)
{
//SearchFunction(exp, s, d);
nod* op = new nod();
int last = 0, Wh[1000], nr = 0;
char Op[1000];
if (exp == "")
{
op->val = 0;
return op;
}
if (FirstAndLastPar(exp))
return Evaluare(exp.substr(1, exp.size()-2));
for (int i = 0; i < exp.size(); i++)
if (exp[i] == '(')
last++;
else if (exp[i] == ')')
last--;
else if (last==0)
for (int j = 0; j < nroperatii; j++)
if (exp[i] == Operatii[j])
{
Op[nr] = exp[i];
Wh[nr++] = i;
break;
}
for (int j = 0; j < nroperatii; j++)
for (int i = 0; i < nr; i++)
if (Op[i]==Operatii[j])
{
op->sp = Operatii[j];
op->op1 = Evaluare(exp.substr(0, Wh[i]));
op->op2 = Evaluare(exp.substr(Wh[i] + 1, string::npos));
return op;
}
op->val = StrToDouble(exp);
return op;
}
double GetValue(nod* act)
{
if (act->sp != "")
{
if (act->sp == "+")
return GetValue(act->op1) + GetValue(act->op2);
if (act->sp == "-")
return GetValue(act->op1) - GetValue(act->op2);
if (act->sp == "*")
return GetValue(act->op1) * GetValue(act->op2);
if (act->sp == "/")
return GetValue(act->op1) / GetValue(act->op2);
}
else
return act->val;
}