Cod sursa(job #2275777)

Utilizator andra1782Andra Alazaroaie andra1782 Data 3 noiembrie 2018 16:27:28
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <stdio.h>
#include <ctype.h>
#define MAX 100000
FILE *fin,*fout;
char ch;
char tip[MAX];//0=semn, 1=numar
int p[MAX],poz,st[MAX];

void e();

int num(){
  int r=0;

  while(isdigit(ch)){
    r=r*10+ch-'0';
    ch=fgetc(fin);
  }
  return r;
}

void f(){
  ch=fgetc(fin);
  if(ch=='('){
      e();
      ch=fgetc(fin);
  }else{
    p[poz]=num();
    tip[poz++]=1;
  }
}

void t(){
  f();
  while(ch=='*' || ch=='/'){
    char aux=ch;
    f();
    p[poz++]=aux;
  }
}

void e(){
  t();
  while(ch=='+' || ch=='-'){
    char aux=ch;
    t();
    p[poz++]=aux;
  }
}

int eval(){
    int i=0,k=0;
    while(i<poz)
        if(!tip[i]){
            switch(p[i]){
                case '+': st[k-2]+=st[k-1]; break;
                case '-': st[k-2]-=st[k-1]; break;
                case '*': st[k-2]*=st[k-1]; break;
                case '/': st[k-2]/=st[k-1]; break;
            }
            k--;
            i++;

        }else
            st[k++]=p[i++];
    return st[0];
}

int main(){
  fin=fopen("evaluare.in","r");
  fout=fopen("evaluare.out","w");

  e();
  fprintf(fout,"%d\n",eval());
  fclose(fin);
  fclose(fout);
  return 0;
}