我认为这是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;

10-04 10:30