Cod sursa(job #1552082)

Utilizator stoianmihailStoian Mihail stoianmihail Data 17 decembrie 2015 11:12:05
Problema Evaluarea unei expresii Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.83 kb
#include <stdio.h>
#include <ctype.h>

char c;
FILE *f;
int E(), T(), F();

/** Da-mi urmatorul caracter din fisier. **/
void getChar() {
  c = fgetc(f);
  while (isspace(c)) {
    c = fgetc(f);
  }
}

/** Citeste urmatorul numar din fisier. **/
void read(int *result) {
  *result = 0;
  do {
    *result = (*result << 3) + (*result << 1) + c - '0';
    getChar();
  } while (isdigit(c));
}

/** Evalueaza expresia. **/
int E() {
  int result = T();
  
  while ((c == '+') || (c == '-')) {
    char save = c;

    getChar();
    result += (save == '+') ? T() : -T();
  }
  return result;
}

/** Evalueaza un termen. **/
int T() {
  int result = F();

  while ((c == '*') || (c == '/')) {
    char save = c;

    getChar();
    if (save == '*') {
      result *= F();
    } else {
      result /= F();
    }
  }
  return result;
}

/** Evalueaza un factor. **/
int F() {
  int result;

  /* Daca dam direct de o alta expresie. */
  if (c == '(') {
    getChar();
    result = E();
    getChar();
  /* Daca avem in fata semnul -. */
  } else if (c == '-') {
    getChar();
    /* O alta expresie. */
    if (c == '(') {
      getChar();
      result = -E();
      getChar();
    /* Un numar negativ. */
    } else if (isdigit(c)) {
      read(&result);
      result = -result;
    }
  /* Daca avem in fata semnul +. */
  } else if (c == '+') {
    getChar();
    /* O alta expresie. */
    if (c == '(') {
      getChar();
      result = E();
      getChar();
    /* Numar pozitiv. */
    } else if (isdigit(c)) {
      read(&result);
    }
  /* Numar obisnuit(pozitiv). */
  } else if (isdigit(c)) {
    read(&result);
  }
  return result;
}

int main(void) {
  f = fopen("evaluare.in", "r");

  getChar();

  freopen("evaluare.out", "w", stdout);
  fprintf(stdout, "%d\n", E());
  fclose(f);
  fclose(stdout);

  /// Multumim Doamne!
  puts("Doamne ajuta!");
  return 0;
}