Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        6年前关闭。
                    
                
        

\帮帮我!我的作业要在今晚12点前完成,我似乎无法让我的程序输出负数为-1/4而不是1 / -4!这让我很沮丧,因为事实是,我不能只在数字前加一个“-”(正如您在下面的程序中看到的那样,我已将其注释掉了)。
我试图将分数设为-1/4(仅以该分数为例)是在“ public RationalNumber(int ...){行下:您看到我写有* -1的部分了吗?在导致我得到1 / -4的那一步出错了?这让我感到沮丧...在此先感谢。

private int n;
private int d;
public RationalNumber(int numerator, int denominator) {
    if (denominator == 0) {
        throw new IllegalArgumentException();
    }
    if (denominator < 0) {
        denominator = denominator * -1;
        numerator = numerator * -1;
      }
    n = numerator;
    d = denominator;
    simplified();
}

public RationalNumber add(RationalNumber rn) {
    int comDenom = d * rn.getDenominator();
    int num1 = n * rn.d;
    int num2 = rn.n * d;
    d = comDenom;
    return new RationalNumber(num1 + num2, d);
}

public RationalNumber subtract(RationalNumber rn) {
    int num1 = n * rn.d;
    int num2 = rn.n * d;
    return new RationalNumber(num1 - num2, d);
}

public RationalNumber multiply(RationalNumber rn) {
    int numer = n * rn.n;
    int denom = d * rn.d;
    return new RationalNumber(numer, denom);
}

public RationalNumber divide(RationalNumber rn) {
    int numer = n * rn.d;
    int denom = d * rn.n;
    return new RationalNumber(numer, denom);
}

public RationalNumber() {
    n = 0;
    d = 1;
}

public boolean equals(RationalNumber o) {
    return (n == o.getNumerator() && d == o.getDenominator());
}

public int getDenominator() {
    return d;
}

public int getNumerator() {
    return n;
}

public String toString() { //Prints everything here.
    if (d == 1) {
        return "" + n;
    }
    if (n == 0) {
        return "0";
    }
    /*if ((n < 0) || (d < 0)) {
        return "-" + Math.abs(n) + "/" + Math.abs(d);
    }*/
    return n + "/" + d;
}

private void simplified() {
     if (n != 0) {
         int cDenom = gcd(n, d);
         n = n / cDenom;
         d = d / cDenom;
     }
}

private int gcd(int gcdNum1, int gcdNum2) {
    while (gcdNum1 != 0 && gcdNum2 != 0) {
        int tempNum = gcdNum2;
        gcdNum2 = gcdNum1 % gcdNum2;
        gcdNum1 = tempNum;
    }
    return gcdNum1 + gcdNum2;
}

最佳答案

问题是gcd()方法可能返回否定结果。调用simplified()方法时,将nc除以可能为负的数字,然后更改其符号。要解决此问题,可以更改gcd()方法以始终返回肯定结果。

更改此行:

return gcdNum1 + gcdNum2;




if (gcdNum1 + gcdNum2 < 0) {
    return -(gcdNum1 + gcdNum2);
} else {
    return gcdNum1 + gcdNum2;
}


然后检查是否得到正确的结果。

09-04 16:20