0

我目前正在进行的项目要求程序将两个分数相加,并简化答案。我已经把分数加在一起了,但我不知道如何简化分数。

PS 到目前为止,我在顶部看到的所有内容都非常令人困惑,如果你能让答案变得简单,谢谢!

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;

}
}
4

1 回答 1

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.

现在,既Integer没有 Number也没有Math方法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);
    }
}

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

于 2013-05-31T16:39:27.387 回答