我如何正确地创建类Ratio add(Ratio r)?

时间:2019-04-10 03:46:00

标签: java

对于我的作业,我得到了基本代码,并被告知要填写这些类,以便它们在加,减,乘和除小数时都能正常工作。我需要帮助来了解比率r的工作原理吗?我的老师告诉我“用分子和分母“ this”所携带的值来完成计算”?

根据他所说的,我觉得我的数学本身是正确的,只是不确定如何返回r?

我尝试使用比率“ r”,但似乎无法弄清楚它是如何工作的。

我当前将r设置为等于的方式不起作用,它说“无法从long类型转换为ratio”

// class level variables
private long _numerator;
private long _denominator;

public Ratio()
{
    long _numerator = 0;
    long _denominator = 1;


}// end of Ratio()

public Ratio(long a)
{
    a = 0;
    _denominator = 1;

}// end of Ratio(long a)

public Ratio(long dividend, long divisor) throws ArithmeticException
{

    this._numerator = dividend;

    // check denominator for 0
    if (divisor == 0)
    {
        throw new ArithmeticException("Denominator cannot be zero");
    } else
        this._denominator = divisor;
    // check for negative
    if (dividend < 0 && divisor < 0) // if there's a negative in numerator and denominator, fraction becomes
                                        // positive
    {
        dividend *= -1;
        divisor *= -1;
    } else if (divisor < 0) // if negative is in denominator, moves negative to the numerator
    {
        dividend *= -1;
        divisor *= -1;
    }

    // simplify fraction in here using gcd
    gcd(dividend, divisor);

}// end of Ratio(long dividend...)

long getNumerator()
{
    return _numerator;
}

long getDenominator()
{
    return _denominator;
}

public Ratio add(Ratio r)
{

    long num= this._numerator;
    long den = this._denominator;
    long otherDen = getDenominator();
    long otherNum = getNumerator(); 
    r = new Ratio();

    //is this the return way to do it?
    r = ((num * otherDen) + (otherNum * den)) / (den * otherDen);

    //or do i have to seperate numerator & denominator?
    long newNum = ((num * otherDen) + (otherNum * den));
    long newDen = (den * otherDen);

    return r();
}// end of add

1 个答案:

答案 0 :(得分:1)

Ratio对象包含两个字段后,您必须用新计算的分子和分母填充它们,然后简单地返回对象new Ratio(resultNumerator, resultDenominator)

public Ratio add(Ratio r) {
    long otherDen = getDenominator();
    long otherNum = getNumerator(); 
    long resultDenominator = this._denominator * otherDen;
    long resultNumerator = this._numerator * otherDen + otherNum * this._denominator;

    return new Ratio(resultNumerator, resultDenominator);
}