分数的简化

时间:2013-05-31 14:09:01

标签: java fractions simplify

我目前正在研究的项目要求程序分为两部分,将它们加在一起并简化答案。我已经完成了将馏分加在一起就好了,但我无法弄清楚如何简化馏分。

P.S。到目前为止我在顶部看到的所有内容实际上都令人困惑,如果你能让答案变得简单,它会有所帮助 谢谢!

import java.io.*;
import java.util.*;
import static java.lang.Math.*;

public class Fractions {

public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.println("Numerator A");
int NuA = Scan.nextInt();
System.out.println("Denominator A");
int DeA = Scan.nextInt();
System.out.println("Numerator B");
int NuB = Scan.nextInt();
System.out.println("Denominator B");
int DeB = Scan.nextInt();

double NumA = NuA * DeB;
double NumB = NuB * DeA;
double Denominator= DeA * DeB;

double Numerator=NumA + NumB;

}
}

1 个答案:

答案 0 :(得分:0)

首先,请记住如何将分数减少到最低分。给定整数ab

a/b == (a/m)/(b/m)  where m is the greatest common divisor of a and b.

使用欧几里德算法最容易获得最大的公约数,即数学中的gcd(a,b)或只是(a,b):

(111, 45) == (21, 45) since 111 = 2 * 45 + 21.
          == (45, 21)
          == (3, 21)  since 45 = 2 * 21 + 3
          == (21, 3)
          == (0, 3)   since 21 = 7 * 3 + 0.
          == 3        stop when one number is zero.

现在,IntegerNumberMath都没有gcd方法,只有在你学习算法的时候才应该自己写一个。{但是,BigInteger具有该方法。因此,创建一个Fraction类。我们将它变为不可变,因此我们可以扩展Number,因此我们应该在构建它时将其减少到最低项。

public class Fraction extends Number {
    private final BigInteger numerator;
    private final BigInteger denominator;
    public Fraction(final BigInteger numerator, final BigInteger denominator) {
        BigInteger gcd = numerator.gcd(denominator);
        // make sure negative signs end up in the numerator only.
        // prefer 6/(-9) to reduce to -2/3, not 2/(-3).
        if (denominator.signum() == -1) {
             gcd = gcd.negate();
        } 
        this.numerator = numerator.divide(gcd);
        this.denominator = denominator.divide(gcd);
    }
}

现在,添加其余的数学例程。请注意,我没有对nulls,除零,无穷大或NaN做任何事情。

相关问题