gpt4 book ai didi

java - 如何创建一个 Java 方法来简化分数?

转载 作者:行者123 更新时间:2023-12-02 07:15:38 26 4
gpt4 key购买 nike

我编写了一个 Fraction 类,但在简化方面遇到了麻烦。

当我制作 Fraction 对象时,一切正常,我只是认为我的逻辑因简化而困惑。

(num和den分别是类中分子和分母的私有(private)变量)

这是我的 GCD 和简化方法:

/**
* Returns the absolute value of the greatest common divisor of this
* fraction's numerator and denominator. If the numerator or denominator is
* zero, this method returns 0. This method always returns either a positive
* integer, or zero.
*
* @return Returns the greatest common denominator
*/
private int gcd() {
int s;
if (num > den)
s = den;
else
s = num;
for (int i = s; i > 0; i--) {
if ((num % i == 0) && (den % i == 0))
return i;
}
return -1;
}

/**
* Changes this fraction's numerator and denominator to "lowest terms"
* (sometimes referred to as a "common fraction"), by dividing the numerator
* and denominator by their greatest common divisor. This includes fixing
* the signs. For example, if a fraction is 24/-18, this method will change
* it to -4/3. If the numerator or denominator of the fraction is zero, no
* change is made.
*/
public void simplify() {

if (isZero() == false) {// Making sure num or den is not zero.
this.fixSigns(); // Fix signs first

if (gcd() > 1) {
this.num = num / gcd();
this.den = num / gcd();
}
}
}

最佳答案

我立即看到两件事:对于每个分子和分母,您将 num 除以 gcd() 两次。此外,一旦更改了分子,则调用 gcd() 的结果可能会发生变化。调用“gcd”一次,存储其结果,并在以后使用它:

int gcd = gcd();
if (gcd > 1) {
this.num = this.num / gcd;
this.den = this.den / gcd;
}

此外,还有更有效的方法来获取最大公约数: Wikipedia's page 。请参阅该页面上的欧几里得算法。

关于java - 如何创建一个 Java 方法来简化分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14964992/

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