使用有理数的Java方法

使用有理数的Java方法,java,rational-number,Java,Rational Number,我有一个有理类和一个主类。我的很多代码都是在rational类中完成的,然后我在主类中调用它。然而,有几个有理数并不像实数那样印刷出来。它们看起来是这样的:理性。Rational@7852e922. 我不知道如何正确地打印它们。此外,在add方法中添加了有理数之后,我无法理解如何使用reduce方法。主类中的最后一行代码出现错误 public class Rational { /** * @param args the command line arguments */ double n

我有一个有理类和一个主类。我的很多代码都是在rational类中完成的,然后我在主类中调用它。然而,有几个有理数并不像实数那样印刷出来。它们看起来是这样的:理性。Rational@7852e922. 我不知道如何正确地打印它们。此外,在add方法中添加了有理数之后,我无法理解如何使用reduce方法。主类中的最后一行代码出现错误

public class Rational {

/**
 * @param args the command line arguments
 */

double num;
double den;

public Rational() {
    this.num = 0.0;
    this.den = 0.0;
}

public static void printRational(Rational r) {
    System.out.println(r.num + " / " + r.den);
}

public Rational(double num, double den) {
    this.num = num;
    this.den = den;
}

public static void negate(Rational r) {
    r.num = -r.num;
}

public static double invert(Rational r) {
    return Math.pow(r.num / r.den, -1);
}

public double toDouble() {
    return (double) num / den;
}

public static int gcd(int n, int d) {
    if (n < 0) {
        n = -n;
    }
    if (d < 0) {
        d = -d;
    }
    return n * (d / gcd (n, d));
}

public Rational reduce() {
    double g = num;
    double gcd = den;
    double tmp;
    if (g < gcd) {
        tmp = g;
        g = gcd;
        gcd = tmp;
    }
    while (g != 0) {
        tmp = g;
        g = gcd % g;
        gcd = tmp;
    }
    return new Rational(num / gcd, den / gcd);
}

public static Rational add(Rational a, Rational b) {
    double den = a.den * b.den;
    double num = a.num * b.num;
    return new Rational(num, den);
}
}

您需要重写Rational中的
toString()
方法

e、 g


将此方法添加到您的
Rational
类:

@Override
public String toString() {
    return printRational(this);
}

toString
的默认实现将只提供其哈希代码的类名和十六进制字符串。

添加了定义谢谢,成功了!:)
public String toString() {
    return num + " / " + den;
}
@Override
public String toString() {
    return printRational(this);
}