Expressão matemática em C
Publicado por ??? (última atualização em 07/08/2013)
[ Hits: 5.515 ]
Esse é um simples exemplo de expressão matemática em C.
Operações:
01 - Soma.
02 - Subtração.
03 - Multiplicação.
04 - Divisão.
...
Compilado/testado nos compiladores GCC e Visual C.
//-------------------------------------------------------------------
//
// THANKS TO:
// 01 - The only GOD, creator of heaven and earth, in the name of JESUS CHRIST.
//
// DESCRIPTION:
// Simple Arithmetic Expression Parser:
//
// This program execute in Windows and Linux ...
//
// FILE:
// expression.c
//
//
// EXPRESSION WITH:
// +
// -
// *
// /
//
// COMPILE:
// gcc expression.c -o expression -O2 -Wall
//
// BY: gokernel - gokernel@hotmail.com
//
//-------------------------------------------------------------------
#include <stdio.h>
#include <string.h> // strcmp(), strlen()
#include <stdlib.h> // malloc()
#include <ctype.h> // isalpha (), isdigit ()
#define TYPE_NUMBER 1
#define ARRAY_MAX 100
static int
operation, // 0, +, -, *, /
array_count,
erro
;
static char
*str,
token [1024],
array [ARRAY_MAX][20]
;
//-------------------------------------------------------------------
// prototypes:
//-------------------------------------------------------------------
//
int get_token (void);
void calculate (int op);
void expression (char *s);
int get_token (void)
{
char *temp;
label_top:
// remove_space
//
while (*str && (*str >= 1 && *str <= 32))
str++;
if (*str == 0)
return 0;
temp = token;
*temp = 0;
if (isdigit(*str))
{
while (isdigit(*str) || *str == '.') *temp++ = *str++;
*temp = 0;
return TYPE_NUMBER;
}
else
if (*str == '-' && isdigit(str[1])) // negative
{
*temp++ = *str++;
while (isdigit(*str) || *str == '.') *temp++ = *str++;
*temp = 0;
return TYPE_NUMBER;
}
else
if (*str == '+' || *str == '-' || *str == '*' || *str == '/')
{
operation = *str;
*temp++ = *str++;
*temp = 0;
return operation;
}
if (*str <= 32)
goto label_top;
erro = 1;
printf ("ERRO - Ilegal Char: '%c'\n", *str);
return 0;
}
void calculate (int op)
{
register int i, a;
label_top:
for (i = 0; i < array_count; i++)
if (array[i][0] == op)
{
switch (op) {
case '/':
sprintf (array[i-1], "%f", atof(array[i-1]) / atof(array[i+1]));
break;
case '*':
sprintf (array[i-1], "%f", atof(array[i-1]) * atof(array[i+1]));
break;
case '+':
sprintf (array[i-1], "%f", atof(array[i-1]) + atof(array[i+1]));
break;
case '-':
sprintf (array[i-1], "%f", atof(array[i-1]) - atof(array[i+1]));
break;
}// switch()
array_count -= 2;
// move the list to top
//
for (a = i; a < array_count; a++)
{
strcpy (array[a], array[a+2]);
}
}//if (array[i][0] == op)
// ! if exist: '+', '-', '*', '/'
//
for (i = 0; i < array_count; i++)
if (array[i][0] == op && array[i][1] == 0)
goto label_top;
}
void expression (char *s)
{
str = s;
operation = 0;
erro = 0;
array_count = 0;
// store in array
//
while (get_token() && !erro)
strcpy(array[array_count++], token);
// !get erro
//
if (!isdigit(array[0][0]) && array[0][1] == 0)
{
erro = 1;
printf ("\nPlease, start with NUMBER ...\n");
return;
}
calculate ('/');
calculate ('*');
calculate ('+');
calculate ('-');
if (!erro)
printf ("__________ = %f\n", atof(array[0]) );
else
printf ("\n<<<<<<<<<< ERRO >>>>>>>>>>\n");
}
int main (int argc, char *argv[])
{
char string [1024];
printf (
"_____________________________________________________________________\n\n"
" Glory and honor to the only God, creator of heaven and earth\n"
" in the name of JESUS CHRIST !\n\n"
" Examples:\n"
" 10 + 20 + 30 * 2 * 3\n\n"
" 30 * 2 + 10 + 20\n\n"
" 10 + 20 + 30\n\n"
" 10 + 20 / 3 * 2\n\n"
" 10 + 20 / 3 * 2 * 5\n\n"
" For 'quit' type: q, quit\n\n"
" BY: gokernel - gokernel@hotmail.com\n"
"_____________________________________________________________________\n"
);
for (;;)
{
printf ("expression > ");
gets (string);
if (strlen(string) >= 1)
{
if ( (!strcmp(string, "q")) || (!strcmp(string, "quit")) )
break;
expression (string);
}
}
printf ("Exiting with sucess: %d", 10 * 10 * 3);
return 0;
}
Assembler 8086 - Simples código que mostra horas e minutos em pontos
Escrita de um número em hexadecimal na tela em Assembly Puro para Linux x86 (GNU Assembly)
Escrita de número em hexadecimal em Assembly Puro para Linux 64bits (Nasm - Netwide Assemble)
Nenhum comentário foi encontrado.
File Browser: Crie sua Nuvem Pessoal Privada
A produção de áudio e vídeo no Linux e as distribuições dedicadas a esse fim
Criptografando sua Home com Gocryptfs para tristeza do meliante
A Involução do Linux e as Lambanças Desnecessárias desde o seu Lançamento
O Journal no Linux para a guarda e consulta de logs do sistema
Gerenciamento de Vídeo Híbrido (Intel/NVIDIA) via nvidia-prime no Ubuntu e derivados
Assistindo IPTV no Linux com Fred TV e Lista Free TV
Impressora Tomate MDK-007 no Ubuntu (ou qualquer distro Linux)
Acelerando a compilação de pacotes no Arch Linux (AUR) usando todos os núcleos do processador
Warsaw não é reconhecido no Google Chrome 147.0.7727.55 [RESOLVIDO] (11)
Depois não querem que eu fale sobre as baseadas... (5)
Tive um problema ao abrir minha partição Btrfs. Como posso resolver is... (0)









