Cod sursa(job #2791637)

Utilizator teochess2017Togan Teodor-Bogdan teochess2017 Data 30 octombrie 2021 21:31:16
Problema Evaluarea unei expresii Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char first;
int n,put;
FILE *fin,*fout;
void readInt(){
  n=0;
  put=1;
  while(isdigit(first=fgetc(fin))){
    n=n*10+first-'0';
    put*=10;
  }
}
int fact(){
  int rez=0;
  char ch='+',aux;
  first=fgetc(fin);
  while((first!=')')&&(first!='\n')){
    if(first=='('){
      if(ch=='+'){
        n=fact();
      }else if(ch=='-'){
        n=-fact();
      }
      if((first=='*')||(first=='/')){
        n=term();
      }
      rez+=n;
      ch=first;
    }else if(('0'<=first)&&(first<='9')){
      aux=first;
      readInt();
      n=n+(aux-'0')*put;
      if((first=='*')||(first=='/')){
        if(ch=='+'){
          rez+=term();
        }else{
          rez-=term();
        }
      }else if(ch=='+'){
        rez+=n;
      }else{
        rez-=n;
      }
      ch=first;
    }else{
      ch=first;
      first=fgetc(fin);
    }
  }
  if(first!='\n'){
    first=fgetc(fin);
  }
  return rez;
}
int term(){
  int rez=n;
  char aux;
  while((first=='*')||(first=='/')){
    if(first=='*'){
      first=fgetc(fin);
      if(first=='('){
        n=fact();
      }else{
        aux=first;
        readInt();
        n=n+(aux-'0')*put;
      }
      rez*=n;
    }else{
      first=fgetc(fin);
      if(first=='('){
        n=fact();
      }else{
        aux=first;
        readInt();
        n=n+(aux-'0')*put;
      }
      rez/=n;
    }
  }
  return rez;
}
int main()
{
    int rez;
    fin=fopen("evaluare.in","r");
    rez=fact();
    fclose(fin);
    fout=fopen("evaluare.out","w");
    fprintf(fout,"%d",rez);
    fclose(fout);
    return 0;
}