\帮助!我的作业要在今晚 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;
}