对于我的家庭作业,我得到了基本代码,并被告知要填写这些类,以便它们在加,减,乘和除小数时都能正常工作。我需要帮助来了解比率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
最佳答案
一旦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);
}
关于java - 我如何正确地创建类Ratio add(Ratio r)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55604475/