我在使用添加,减去和分割分数的方法时遇到了麻烦。我有乘法部分我只是在添加时遇到正确的输出问题。请帮我弄清楚我做错了什么我是Java新手,我还在学习。这是我到目前为止所得到的.`
private int numer;
private int denom;
public Fraction(int num, int den) {
numer = num;
denom = den;
simplify();
}
public int findGcd(int a, int b) {
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
void simplify() {
int gcd = findGcd(numer, denom);
numer /= gcd;
denom /= gcd;
}
public int getNumer() {
return numer;
}
public int getDenom() {
return denom;
}
Fraction add(Fraction x) {
Fraction answer;
if (x.getDenom() == denom) {
answer = new Fraction(x.getNumer() + numer, denom);
} else {
denom = this.getDenom() * x.getDenom();
numer = this.getNumer() * x.getDenom() + x.getNumer()
* this.getDenom();
return new Fraction(numer, denom);
}
return answer;
}
Fraction subtract(Fraction x) {
Fraction answer;
if (x.getDenom() == denom) {
answer = new Fraction(x.getNumer() - numer, denom);
} else {
denom = this.getDenom() * x.getDenom();
numer = this.getNumer() * x.getDenom() - x.getNumer()
* this.getDenom();
answer = new Fraction(numer, denom);
}
return answer;
}
Fraction mult(Fraction x) {
Fraction answer;
denom = this.getDenom() * x.getDenom();
numer = this.getNumer() * x.getNumer();
answer = new Fraction(numer, denom);
return answer;
}
Fraction div(Fraction x) {
Fraction answer;
denom = this.getDenom() * x.getNumer();
numer = this.getNumer() * x.getDenom();
answer = new Fraction(numer, denom);
return answer;
}
当我输入2个分数时,它返回一个分数,但它不是正确的答案。我做错了什么?
如果我使用小分数例如1/2和3/4它仍然给我错误的答案。对于添加,它打印出7/2,减法1/2和除法3/1。因此,我不认为必须做int
或float
号码。
答案 0 :(得分:2)
在您的函数中,您将覆盖数字和denom的值。变化:
denom = this.getDenom() * x.getDenom();
numer = this.getNumer() * x.getDenom() - x.getNumer()
* this.getDenom();
answer = new Fraction(numer, denom);
到
int newdenom = this.getDenom() * x.getDenom();
int newnumer = this.getNumer() * x.getDenom() - x.getNumer()
* this.getDenom();
answer = new Fraction(newnumer, newdenom);