gpt4 book ai didi

java - 如何正确创建类 Ratio add(Ratio r)?

转载 作者:行者123 更新时间:2023-12-02 10:01:23 24 4
gpt4 key购买 nike

在我的家庭作业中,我得到了框架代码,并被告知要填写这些类,以便它们在分数加、减、乘、除时能够正常工作。我需要帮助了解 Ratio r 到底是如何工作的?我的老师告诉我“它携带的值可以用“这个”携带的分子和分母来完成计算”?

根据他的说法,我觉得我的数学本身是正确的,只是不确定如何返回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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com