Cod sursa(job #2669566)

Utilizator gafton13andreeaGafton Andreea gafton13andreea Data 7 noiembrie 2020 11:33:55
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>

using namespace std;
char s[1000] ;
stack <char> semne;
stack <int> numere;

int calcul(int a, int b, char o)
{
 if(o=='*')
        return a*b;
 if(o=='-')
    return a-b;
 if(o=='+')
    return a+b;
 if(o=='/')
    return a/b;
}

int ordine(char x)
{
    if(x==')')
        return -1;
    if(x=='(')
        return 0;
  if(x=='+' || x=='-')
        return 1;
  if(x=='*' || x=='/')
    return 2;
}

void formare()
{
 int n=strlen(s),ok=1;
 for(int i=0;i<n;++i)
 {
      if(s[i]<'0' || s[i]>'9')
      {

       if(semne.empty() || s[i]=='(' || ordine(s[i])>ordine(semne.top()))
         semne.push(s[i]);

      else
      {
          if(s[i]==')')
          {
              while(semne.top()!='(')
          {
            int a=numere.top();
          numere.pop();
           int b=numere.top();
          numere.pop();
          numere.push(calcul(b,a,semne.top()));
          semne.pop();
          }
          semne.pop();
          }

          else
          {
        int a=numere.top();
          numere.pop();
           int b=numere.top();
          numere.pop();
          numere.push(calcul(b,a,semne.top()));
          semne.pop();

            semne.push(s[i]);
          }


      }
      }
      else
       numere.push(s[i]-'0');
       //cout<<numere.top()<<'\n';
       //cout<<semne.top()<<'\n';
 }
 int r;
 while(!semne.empty())
 {
    int a=numere.top();
          numere.pop();
           int b=numere.top();
          numere.pop();
         r=(calcul(b,a,semne.top()));
        numere.push(r);
          semne.pop();
 }

    printf("%d", r);


///(1+2*3)*5-(2*3)*(1+1)/3
}

int main()
{
    freopen("evaluare.in", "r", stdin);
    freopen("evaluare.out", "w", stdout);
    gets(s);
    formare();
    return 0;
}
//if((s[i]>'0' || s[i]=='0') && (s[i]<'9' || s[i]=='9'))