用法: public void add(分数其他) public void subtract(分数其他) public void multiply(分数其他)都是void方法。它们不会返回任何内容。这些方法不应该创建新的分数并返回它。
相反,这些方法应该修改实例变量,使之与分数other相加、相减或相乘。我该怎么做呢?
发布于 2020-11-20 11:31:14
对于加法和减法,找到分母的最小公倍数,并将两个分数转换为相等的分母。然后,添加/减去(取决于操作)分子。
对于乘法,只需将两个分子和分母相乘即可。
对于所有运算,在末尾找到新分子和分母的最大公因数,并将它们除以最大公因数。
为了成为void函数,只需编辑第一个分数的分子/分母,而不是返回新的分子/分母。
代码将如下所示:
class Fraction {
int numer;
int denom;
public Fraction(int n, int d) {
numer = n;
denom = d;
}
public void add(Fraction other) {
numer *= other.denom;
other.numer *= denom;
denom *= other.denom;
other.denom = denom;
numer += other.numer;
int gcd = gcd(numer, denom);
numer /= gcd;
denom /= gcd;
}
public void subtract(Fraction other) {
numer *= other.denom;
other.numer *= denom;
denom *= other.denom;
other.denom = denom;
numer -= other.numer;
int gcd = gcd(numer, denom);
numer /= gcd;
denom /= gcd;
}
public void multiply(Fraction other) {
numer *= other.numer;
denom *= other.denom;
int gcd = gcd(numer, denom);
numer /= gcd;
denom /= gcd;
}
public int gcd(int a, int b) {
// code from the website goes here
}希望这一点能得到很好的解释!
发布于 2020-11-20 11:05:53
假设分数看起来像这样:
public class Fraction {
private int numerator = 1;
private int denominator = 2;
public void multiply(Fraction other) {
numerator *= other.getNumerator();
denominator *= other.getDenominator();
}
public int getNumerator() {
return numerator;
}
public int getNumerator() {
return numerator;
}
}希望这能解释这一点。
https://stackoverflow.com/questions/64923171
复制相似问题