[C] Números Racionais

Publicado por Enzo de Brito Ferber (última atualização em 25/04/2017)

[ Hits: 8.453 ]

Homepage: http://www.maximasonorizacao.com.br

Download rational.c




Script que define um TDA (tipo de dados abstracto) chamado RATIONAL para manipular frações (números racionais). Um número racional é qualquer número representado pela razão entre dois intereiros A e B, na forma A/B. O programa implementa funções para criar um número racional a partir de dois inteiros, somar, subtrair, dividir, multiplicar e simplificar.

Compilar com:

gcc -o rational rational.c -Wall -lm

  



Esconder código-fonte

/* rational.c
 * gcc -o rational rational.c -Wall -lm
 *
 *    (C) 2017 - Enzo Ferber, <enzoferber@gmail.com>
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <math.h>

#define MIN(a,b)      (a < b ? a : b)
#define BUF_SIZE      32

struct rational {
   int n; /* numerator */
   int d; /* denominator */
};

typedef struct rational RATIONAL;

void *xmalloc(size_t n)
{
   void *p = malloc(n);
   if(!p) {
      perror("malloc");
      exit(EXIT_FAILURE);
   }
   return p;
}

int GCD(int a, int b)
{
   register int i;

   /* if any is zero, return 1 */
   if(!a || !b) return 1;

   for(i = MIN(a,b); i >= 1; i--) 
      if(!(a % i) && !(b % i)) break;

   return i;
}

RATIONAL *make_rational(int n, int d)
{
   RATIONAL *r = xmalloc(sizeof *r);
   r->n = n;
   r->d = d;
   return r;
}

RATIONAL *simplify_rational(RATIONAL *r)
{
   int m = GCD(r->n, r->d);

   r->n /= m;
   r->d /= m;

   /* just for consistency */
   return r;
}

RATIONAL *add_rational(RATIONAL *a, RATIONAL *b)
{
   RATIONAL *r = xmalloc(sizeof *r);

   r->n = (a->n * b->d) + (b->n * a->d);
   r->d = a->d * b->d;

   return simplify_rational(r);
}

RATIONAL *subtract_rational(RATIONAL *a, RATIONAL *b)
{
   RATIONAL *r = xmalloc(sizeof *r);

   r->n = (a->n * b->d) - (b->n * a->d);
   r->d = a->d * b->d;

   return simplify_rational(r);
}

RATIONAL *divide_rational(RATIONAL *a, RATIONAL *b)
{
   RATIONAL *r = xmalloc(sizeof *r);

   r->n = a->n * b->d;
   r->d = a->d * b->n;

   return simplify_rational(r);
}

RATIONAL *multiply_rational(RATIONAL *a, RATIONAL *b)
{
   RATIONAL *r = xmalloc(sizeof *r);

   r->n = a->n * b->n;
   r->d = a->d * b->d;

   return simplify_rational(r);
}

int read_int(char *label) {
   char buffer[BUF_SIZE];
   fprintf(stderr, label);
   fgets(buffer, BUF_SIZE, stdin);
   return atoi(buffer);
}

RATIONAL *get_rational(void)
{
   int a, b;

   a = read_int("Numerador  : ");
   b = read_int("Denominador: ");

   return make_rational(a, b);
}

void print_rational(char *label, RATIONAL *r)
{
   printf("%s: %d/%d\n", label, r->n, r->d);
}

int main(int argc, char *argv[])
{
   RATIONAL *a, *b, *add, *sub, *mul, *div;

   a = get_rational();
   b = get_rational();

   add = add_rational(a, b);
   sub = subtract_rational(a, b);
   mul = multiply_rational(a, b);
   div = divide_rational(a, b);

   print_rational("A  ", a);
   print_rational("B  ", b);
   print_rational("add", add);
   print_rational("sub", sub);
   print_rational("mul", mul);
   print_rational("div", div);

   free(a);
   free(b);
   free(add);
   free(sub);
   free(mul);
   free(div);

   return 0;
}
/* EoF */

Scripts recomendados

Quadrado Mágico

C join

Exibe quantos números perfeitos foram digitados

Determinando a posicão de ocorrencia de uma string em outra

Linhas Numeradas


  

Comentários
[1] Comentário enviado por removido em 28/04/2017 - 01:04h

Isto me lembrou de um programa que fiz em C++ para este mesmo propósito.
Se eu encontrar, talvez eu faça postagem.

----------------------------------------------------------------------------------------------------------------
Nem direita, nem esquerda. Quando se trata de corrupção o Brasil é ambidestro.
(anônimo)

Encryption works. Properly implemented strong crypto systems are one of the few things that you can rely on. Unfortunately, endpoint security is so terrifically weak that NSA can frequently find ways around it. — Edward Snowden

[2] Comentário enviado por EnzoFerber em 28/04/2017 - 08:06h


[1] Comentário enviado por listeiro_037 em 28/04/2017 - 01:04h

Isto me lembrou de um programa que fiz em C++ para este mesmo propósito.
Se eu encontrar, talvez eu faça postagem.

----------------------------------------------------------------------------------------------------------------
Nem direita, nem esquerda. Quando se trata de corrupção o Brasil é ambidestro.
(anônimo)

Encryption works. Properly implemented strong crypto systems are one of the few things that you can rely on. Unfortunately, endpoint security is so terrifically weak that NSA can frequently find ways around it. — Edward Snowden


Pô, bacana. E o que achou desse código? Alguma sugestão ou crítica?

[3] Comentário enviado por removido em 29/04/2017 - 17:57h

Ficou muto bom. Bem sucinto.
É relativamente parecido com o meu.
Uso de MDC, simplificação.

Algumas diferenças com o meu seriam o uso de classes e polimorfismo.
Como no caso de receber zero e números inteiros onde o denominador fica automático igual a um.

Não me lembro o que fiz com denominador zero. Devo ter me esquecido de usar alguma rotina de verificação.

----------------------------------------------------------------------------------------------------------------
Nem direita, nem esquerda. Quando se trata de corrupção o Brasil é ambidestro.
(anônimo)

Encryption works. Properly implemented strong crypto systems are one of the few things that you can rely on. Unfortunately, endpoint security is so terrifically weak that NSA can frequently find ways around it. — Edward Snowden


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts