0

我正在尝试编写一个 Rational 类,它有一些与加法、减法等相关的方法。我想在构造函数中将值添加到私有变量并找到 GCD 以找到简化分数。我遇到的问题是我的 if 语句。我想检查对象参数中的数字是否为负,所以我使用 if 语句进行检查。唯一的问题是当我运行程序时,它没有给我一个负值,即我有 Rational p = new Rational(-24, 48),它只返回 1/2。

public class TestRational {

    public static void main(String... args) {
        Rational p = new Rational(-24, 48);
    }

    public Rational(long a, long b){
        numerator = a;
        denominator = b;
        boolean isNegative = false;
        if (numerator*denominator < 0)
            isNegative = true;
        long gd = gcd(numerator, denominator);
        numerator /= gd;
        denominator /= gd;
        if (isNegative)
            numerator = -numerator;;
    }

    private long gcd(long p, long q){
        //checks to see if numerator greater than denominator
        if(p<q)
            return gcd(q,p);
        if(Math.abs(q) == 0)
            return p;
        long remainder = Math.abs(p)%Math.abs(q);
        return gcd(Math.abs(q), Math.abs(remainder));
    }
}
4

3 回答 3

5

你不需要这个

if (isNegative)
 numerator = -numerator;;

所以构造函数变成

public Rational(long a, long b){
 numerator = a;
 denominator = b;
 boolean isNegative = false;
 if (numerator*denominator < 0)
 isNegative = true;
 long gd = gcd(numerator, denominator);
 numerator /= gd;
 denominator /= gd;
}

希望它有效...

于 2012-09-18T20:42:54.693 回答
1

除非您的问题明确要求您使用 GCD 并且 and 的范围a不大b,否则您可以简单地使用循环来实现它:

public Rational(long a, long b){
    boolean isNegative = a < 0 || b < 0;
    a = Math.abs(a);
    b = Math.abs(b);
    for (int i = min(a, b); i >= 2; --i)
        if (a % i == 0 && b % i == 0)
        {
            a /= i;
            b /= i;
        }
    numerator = isNegative ? -a : a;
    denominator = b;
}
于 2012-09-18T20:50:02.893 回答
0

我想在您的代码中指出一些“可避免的错误”。

  1. 构造函数的名称必须与类的名称相同。在你的情况下,它不是
  2. if{ statements}使用块,即使它包含单个语句。
  3. 你没有声明局部变量分子分母的类型
  4. 你在说什么私有变量

发布时多注意代码,它将帮助您获得问题的良好答案

于 2012-09-18T21:16:35.977 回答