Pagini recente » Cod sursa (job #2114113) | Cod sursa (job #988648) | Cod sursa (job #3296003) | Cod sursa (job #319545) | Cod sursa (job #1131071)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define N_MAX (int)1e5
char S[ N_MAX + 2 ];
int N, sp;
/*
Syntax:
expr: term [ '+|-' + term ]*
term: fact [ '*|/' + fact ]*
fact: '(' + expr + ')' | num
*/
int expr( );
int term( );
int fact( );
int num( );
int expr( ) {
int ans = term( );
while( S[ sp ] == '+' || S[ sp ] == '-' ) {
if( S[ sp ] == '+' ) {
sp ++;
ans += term( );
} else {
sp ++;
ans -= term( );
}
}
return ans;
}
int term( ) {
int ans = fact( );
while( S[ sp ] == '*' || S[ sp ] == '/' ) {
if( S[ sp ] == '*' ) {
sp ++;
ans *= fact( );
} else {
sp ++;
ans /= fact( );
}
}
return ans;
}
int fact( ) {
int ans = 0;
if( S[ sp ] == '(' ) {
sp ++;
ans = expr( );
sp ++;
} else {
ans = num( );
}
return ans;
}
int num( ) {
int ans = 0;
while( isdigit( S[ sp ] ) ) {
ans = ans * 10 + S[ sp ++ ] - '0';
}
return ans;
}
int main( ) {
FILE * fin, * fout;
fin = fopen( "evaluare.in", "r" );
fout = fopen( "evaluare.out", "w" );
fgets( S, sizeof( S ), fin );
N = strlen( S ) - 1;
printf( "%d\n", N );
fprintf( fout, "%d\n", expr( ) );
fclose( fin );
fclose( fout );
}