Created
April 13, 2020 15:04
-
-
Save parzibyte/98d23d4509ea52d8fbedc9cc2a9e89df 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
/* | |
____ _____ _ _ _ | |
| _ \ | __ \ (_) | | | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___ | |
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \ | |
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/ | |
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___| | |
__/ | __/ | | |
|___/ |___/ | |
Blog: https://parzibyte.me/blog | |
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/ | |
Contacto: https://parzibyte.me/blog/contacto/ | |
Copyright (c) 2020 Luis Cabrera Benito | |
Licenciado bajo la licencia MIT | |
El texto de arriba debe ser incluido en cualquier redistribución | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
// Se debe incluir con "" y no con <>, para que busque de manera relativa | |
#include "tinyexpr.h" | |
#include "tinyexpr.c" | |
int main() { | |
/* | |
Ahora tenemos a las funciones: | |
te_interp | |
te_compile | |
te_eval | |
te_free | |
*/ | |
char *ecuacion = "x * y * z * pow(x, y)"; | |
// Es importante usar el tipo double, y no float | |
double x, y, z; | |
/* | |
Juntamos las variables del programa con las de la expresión. Nota | |
que son punteros, así, podemos modificar las variables más tarde pero | |
la expresión ya estará compilada | |
*/ | |
te_variable variables[] = { | |
{"x", &x}, | |
{"y", &y}, | |
{"z", &z}, | |
}; | |
int numeroVariables = | |
3; // Esto se define manualmente; es la cantidad de variables | |
// Compilamos la expresión, para usarla más tarde. Aquí mismo comprobamos que | |
// no haya errores en la misma | |
te_expr *expresion = te_compile(ecuacion, variables, numeroVariables, 0); | |
if (!expresion) { | |
printf("Error en la expresion"); | |
return EXIT_FAILURE; | |
} | |
/* | |
Llegados a este punto estamos seguros de que la expresión es válida | |
Nota: no es necesario escanear, podrías asignar tú mismo los valores, por | |
ejemplo: x = 1; | |
*/ | |
printf("Vamos a resolver %s\n", ecuacion); | |
printf("Ingresa el valor de x:\n"); | |
scanf("%lf", &x); | |
printf("Ingresa el valor de y:\n"); | |
scanf("%lf", &y); | |
printf("Ingresa el valor de z:\n"); | |
scanf("%lf", &z); | |
// La evaluamos e imprimimos el valor | |
double resultado = te_eval(expresion); | |
printf("Resultado: %f", resultado); | |
// Liberamos el puntero, o mejor dicho, la memoria ocupada por la expresión | |
te_free(expresion); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment