C 中的有理数

发布于 2024-12-22 17:09:27 字数 1168 浏览 1 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

归途 2024-12-29 17:09:27

将有问题的行替换为:

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

Replace the lines in question with:

outrat->numerator = inrat->numerator / a;
outrat->denominator = inrat->denominator / a;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文