c – 有理数

我认为这是tanennmbaum的书籍数据结构中的一个程序

代码是错误的,因为outrat-> numerator / = a;不是有效的

命令,因为它没有分配给它的值,请纠正我,如果我

我错了.请更正代码.

#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;
}

最佳答案 用以下内容替换有问题的行:

outrat->numerator = inrat->numerator / a;
outrat->denominator = inrat->denominator / a;
点赞