Cod sursa(job #271580)

Utilizator UpL1nKPaunescu Sorin UpL1nK Data 5 martie 2009 16:11:06
Problema Evaluarea unei expresii Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

char buffer[100001];
int length;
char *c;

float expresie();
float termen();
float factor();

int main() {

    ifstream fin("evaluare.in");
    ofstream fout("evaluare.out");

    fin.get(buffer, 200);
    buffer[strlen(buffer)] = 0;
    length = strlen(buffer);

    c = buffer;

    fout<<expresie();

    return 0;
}


float expresie() {

    float x = termen();
    while ((*c == '+' || *c == '-') && (c-buffer+1 <= length)) {
	if (*c == '+') {
	    c++;
	    x += termen();
	} else if (*c == '-') {
	    c++;
	    x -= termen();
	}
    }

    return x;


}

float termen() {

    float x=factor();
    while ((*c == '*' || *c == '/') && (c-buffer+1 <= length)) {
	if (*c == '*') {
	    c++;
	    x = x * factor();
	} else if (*c == '/') {
	    c++;
	    x = x / factor();
	}
    }

    return x;

}

float factor() {

    float aux;
    if (isdigit(*c)) {
	aux = atof(c);
	while (isdigit(*c))
	    c++;
    } else {
	if (c-buffer+1 <= length) {
	    c++;
	    aux = expresie();
	    c++;
	}
    }

    return aux;

}