Cod sursa(job #2759222)

Utilizator LucaMihaiLM10Luca Ilie LucaMihaiLM10 Data 16 iunie 2021 11:38:19
Problema Evaluarea unei expresii Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <stdio.h>
#include <ctype.h>

FILE *fin, *fout;
char ch;

void nextChar() {
    ch = fgetc( fin );
    while ( ch == ' ' )
        ch = fgetc( fin );
}

int expresie();

int getNum() {
    int x;

    x = 0;
    while ( isdigit( ch ) ) {
        x = x * 10 + ch - '0';
        nextChar();
    }

    return x;
}

int termen() {
    char semn;
    int rez, x;

    semn = '*';
    rez = 1;
    while ( ch != '+' && ch != '-'  && ch != ')' && ch != '\n' ) {
        if ( ch == '(' )
            x = expresie();
        else
            x = getNum();
        if ( semn == '*' )
            rez *= x;
        else
            rez /= x;
        if ( ch == '*' ) {
            semn = ch;
            nextChar();
        } else if ( ch == '/' ) {
            semn = ch;
            nextChar();
        }
    }

    return rez;
}
int expresie() {
    int rez, semn;

    nextChar();
    semn = 1;
    rez = 0;
    while ( ch != '\n' && ch != ')' ) {
        rez += termen() * semn;
        if ( ch == '+' ) {
            semn = 1;
            nextChar();
        } else if ( ch == '-' ) {
            semn = -1;
            nextChar();
        }
    }
    nextChar();

    return rez;
}

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

    fprintf( fout, "%d", expresie() );

    fclose( fin );
    fclose( fout );

    return 0;
}