我正在为关于javaoop的作业编写代码。我不得不对2个分数做运算,但大多数时候输出是错误的,我不知道为什么。我认为simplify有问题,因为没有simplify的结果是正确的,如果两个分数0/8和6/14,减法应该是-3/7,但是输出是0/1,谢谢你的帮助!代码如下:
class Fraction {
private int numer, denom;
public Fraction(int numerator, int denominator) {
numer = numerator;
denom = denominator;
}
private int euclidGcd(int a, int b) {
int remainder;
while (b > 0) {
remainder = a % b;
a = b;
b = remainder;
}
return a;
}
private Fraction simplify() {
int gcd = euclidGcd(numer, denom);
this.numer = this.numer / gcd;
this.denom = this.denom / gcd;
Fraction result = new Fraction(numer, denom);
return result;
}
public Fraction add(Fraction another) {
int b = this.denom * another.denom;
int a = (b/this.denom) * this.numer + (b/another.denom) * another.numer;
Fraction result = new Fraction(a, b);
result.simplify();
return result;
}
public Fraction minus(Fraction another) {
int b = this.denom * another.denom;
int a = (b/this.denom) * this.numer - (b/another.denom) * another.numer;
Fraction result = new Fraction(a, b); // stub
result.simplify();
return result;
}
public Fraction times(Fraction another) {
int a = this.numer * another.numer;
int b = this.denom * another.denom;
Fraction result = new Fraction(a, b); // stub
result.simplify();
return result;
}
public Fraction divide(Fraction another) {
int a = this.numer * another.denom;
int b = this.denom * another.numer;
Fraction result = new Fraction(a, b); // stub
result.simplify();
return result;
}
public String toString() {
return numer + "/" + denom;
}
1条答案
按热度按时间rur96b6h1#
尝试将减号函数更改为: