Last active
December 28, 2018 16:04
-
-
Save bruno-galdino/71f6f56cc459c8f57b4888c02d2bdd39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Bruno Soares Galdino | |
avaliação de expressões aritméticas - em desenvolvimento | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#include <ctype.h> | |
bool isValue( const char *exp ) | |
{ | |
while(isdigit(*exp++) ); | |
return !*(exp-1); | |
} | |
char *findNextOperator( char *exp ) | |
{ | |
char *aux = NULL; | |
while( *exp ) | |
{ | |
if( *exp == '+' || *exp == '-' ) | |
{ | |
return exp; | |
} | |
else if( !aux && (*exp == '*' || *exp == '/') ) | |
{ | |
aux = exp; | |
} | |
exp++; | |
} | |
return aux; | |
} | |
int *eval( char *begin, char *end ) | |
{ | |
char temp = *end; | |
*end = '\0'; | |
int *result = NULL; | |
int *parcial1,*parcial2; | |
char *operator; | |
if( isValue(begin) ) | |
{ | |
result = malloc(sizeof(int) ); | |
*result = atoi(begin); | |
} | |
else | |
{ | |
operator = findNextOperator( begin ); | |
if( operator ) | |
{ | |
result = malloc(sizeof(int) ); | |
parcial1 = eval( begin, operator); | |
parcial2 = eval( operator + 1, end); | |
switch(*operator ) | |
{ | |
case '*': *result = *parcial1 * *parcial2; break; | |
case '/': if(!*parcial2) exit(0); *result = *parcial1 / *parcial2; break;/*fecha o programa em divisão por zero*/ | |
case '+': *result = *parcial1 + *parcial2; break; | |
case '-': *result = *parcial1 - *parcial2; break; | |
} | |
free( parcial1); | |
free( parcial2); | |
} | |
} | |
*end = temp; | |
return result; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
char exp[ ] = "40-3*6/0";/*não utilizar espaços em branco, a rotina não trata isso por enquanto*/ | |
int *ret = eval( exp, exp + sizeof exp ); | |
if( ret ) | |
{ | |
printf("%d",*ret); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment