gpt4 book ai didi

java - 对 2 个分数的操作

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:48:58 24 4
gpt4 key购买 nike

我正在为有关 Java OOP 的作业编写代码。我必须对 2 个分数进行运算,但大多数时候输出是错误的,我不知道为什么。我认为简化有问题,因为结果是正确的而没有简化如果两个分数 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;
}

最佳答案

尝试将负函数更改为:

public Fraction minus(Fraction another) {
return new Fraction(this.numer * another.denom - another.numer * this.denom, this.denom * other.denom).simplify();
}

关于java - 对 2 个分数的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47036483/

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