Cod sursa(job #1770428)

Utilizator danielNiculaeDaniel Niculae danielNiculae Data 4 octombrie 2016 13:04:02
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.62 kb
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/* 
 * File:   evaluare.cpp
 * Author: octavian
 *
 * Created on 03 October 2016, 15:22
 */

#include <cstdlib>
#include <cstdio>

using namespace std;

const int EXPR_LENGTH = 100005;

int location = 0;
char expr[EXPR_LENGTH];

FILE *fin = fopen("evaluare.in", "r");
FILE *fout = fopen("evaluare.out", "w");


int getFactor();
int getMultiplication();
int getSum();

int getFactor() {
//    fprintf(fout, "getFactor()\n");
//    fflush(fout);
    int term = 0;
//    fprintf(fout, "location: %d\n", location);
//    fflush(fout);
//    fprintf(fout, "expr[location]: %c\n", expr[location]);
//    fflush(fout);
    if(expr[location] == '(') {
        ++location;
        term = getSum();
        ++location;
    } else {
        do {
            term = 10 * term + expr[location] - '0';
            ++location;
        } while('0' <= expr[location] && expr[location] <= '9');
    }
//    fprintf(fout, "returning %d: ", term);
//    fflush(fout);
    return term;
}

int getMultiplication() {
//    fprintf(fout, "getMultiplication()\n");
//    fflush(fout);
    int sum = getFactor();
    while(expr[location] == '*' || expr[location] == '/') {
        char op = expr[location++];
        int b = getFactor();

        switch(op) {
            case '*': {
                sum *= b;
                break;
            }
            case '/': {
                sum /= b;
            }
        }  
    }
    return sum;
}

int getSum() {
//    fprintf(fout, "getSum()\n");
//    fflush(fout);
    
    int sum = getMultiplication();
    
//    fprintf(fout, "%c\n", op);
//    fflush(fout);
    while(expr[location] == '+' || expr[location] == '-') {
        
        char op = expr[location++];
        int b = getMultiplication();
        
//        fprintf(fout, "op: %c\n", op);
//        fprintf(fout, "b: %d\n", b);
//        fflush(fout);
       
        switch(op) {
            case '+': {
//                fprintf(fout, "Plus!!!");
                sum = sum + b;
//                fprintf(fout, "sum: %d\n", sum);
                break;
            }
            case '-': {
                sum = sum - b;               
//                fprintf(fout, "sum: %d\n", sum);
            }
        } 
        
    }
    return sum;
}

/*
 * 
 */
int main(int argc, char** argv) {
    

//    fprintf(fout, "Starting to read:\n");
    fscanf(fin, "%s", expr);
//    fprintf(fout, "%s\n", expr);
//    fflush(fout);
    fprintf(fout, "%d\n", getSum());
//    fflush(fout);
    

    return 0;
}