Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rational numbers in C

This is a program in the book data structures by tanennmbaum, I think the code is wrong because outrat->numerator/=a; is not a valid command, because it has no value assigned to it, please correct me if I am wrong. Please, correct the code.

#include <iostream.h>
#include <conio.h>
#include <stdio.h>

struct rational
{
  int numerator;
  int denominator;
};

void reduce(struct rational *inrat, struct rational *outrat)
{
  int a, b, rem;

  if (inrat->numerator > inrat->denominator)
  {
    a = inrat->numerator;
    b = inrat->denominator;
  }
  else
  {
    a = inrat->denominator;
    b = inrat->numerator;
  }

  while (b != 0)
  {
    rem = a % b;
    a = b;
    b = rem;
  }

  outrat->numerator /= a;
  outrat->denominator /= a;
}

int equal(struct rational *rat1, struct rational *rat2)
{
  struct rational r1, r2;

  reduce(rat1, &r1);
  reduce(rat2, &r2);

  if (r1.numerator == r2.numerator && r1.denominator == r2.denominator)
    return 1;

  return 0;
}

int main()
{
  struct rational rn1, rn2;
  int k;

  rn1.numerator = 5;
  rn1.denominator = 10;

  rn2.numerator = 1;
  rn2.denominator = 2;

  k = equal(&rn1, &rn2);

  cout << k;
  getch();

  return 0;
}
like image 519
swe Avatar asked Oct 23 '22 14:10

swe


1 Answers

Replace the lines in question with:

outrat->numerator = inrat->numerator / a;
outrat->denominator = inrat->denominator / a;
like image 196
Robᵩ Avatar answered Oct 27 '22 00:10

Robᵩ