如何制作用于简化分数的 Java 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14964992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make a Java method for simplifying a fraction?
提问by ShanaBoo
I have written a Fraction class, and am having trouble with the simplification.
我写了一个 Fraction 类,但在简化方面遇到了麻烦。
When I make the Fraction object, everything works fine, i just think my logic is messy with the simplification.
当我制作 Fraction 对象时,一切正常,我只是认为我的逻辑因简化而混乱。
(num and den are private variables in the class for numerator and denominator respectively)
(num 和 den 分别是类中分子和分母的私有变量)
Here are my GCD and Simplify methods:
这是我的 GCD 和 Simplify 方法:
/**
* 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();
}
}
}
回答by rgettman
Two things I see right away: You are dividing num
by gcd()
twice, for each of the numerator and denominator. Also, once, you change the numerator, then the result of the call to gcd()
may change. Call "gcd" once, store its result, and use it later:
有两件事情我马上看到:您将num
通过gcd()
两次,每个分子和分母的。此外,一旦您更改了分子,则调用 的结果gcd()
可能会更改。调用“gcd”一次,存储它的结果,并在以后使用它:
int gcd = gcd();
if (gcd > 1) {
this.num = this.num / gcd;
this.den = this.den / gcd;
}
Additionally, there are more efficient ways of obtaining the greatest common divisor: Wikipedia's page. See Euclid's algorithm on that page.
此外,还有更有效的获取最大公约数的方法:维基百科页面。请参阅该页面上的 Euclid 算法。