Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 分数的简化_Java_Fractions_Simplify - Fatal编程技术网

Java 分数的简化

Java 分数的简化,java,fractions,simplify,Java,Fractions,Simplify,我目前正在做的项目要求程序将两个分数相加,并简化答案。我已经很好地完成了分数相加,但我不知道如何简化分数 顺便说一下,到目前为止,我在顶部看到的一切都是令人困惑的,如果你能让答案简单一点,这会有所帮助 谢谢 首先,记住如何将分数减少到最低项。给定整数a和b a/b == (a/m)/(b/m) where m is the greatest common divisor of a and b. 使用欧几里德算法最容易获得数学中的最大公约数gcd(a,b)或(a,b): (111, 45) =

我目前正在做的项目要求程序将两个分数相加,并简化答案。我已经很好地完成了分数相加,但我不知道如何简化分数

顺便说一下,到目前为止,我在顶部看到的一切都是令人困惑的,如果你能让答案简单一点,这会有所帮助 谢谢


首先,记住如何将分数减少到最低项。给定整数
a
b

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
方法,只有在学习算法时,你才应该自己写一个。但是,
biginger
具有该方法。因此,创建一个
分数
类。我们将使它不可变,因此我们可以扩展
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的事情

通常,变量名称的第一个字母较低。Scan->Scan,NumA->NumA和NumB->NumB等。为什么要使用
double
s?分数的分子和分母总是整数……你会在一张纸上/脑子里做什么来简化分数?
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);
    }
}