【问题标题】:simplification of fractions分数的化简
【发布时间】:2013-05-31 14:09:00
【问题描述】:

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

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

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;

}
}

【问题讨论】:

  • 通常变量名的第一个字母较低。扫描 -> 扫描,NumA -> numA 和 NumB -> numB 等
  • 你为什么要使用doubles?分数的分子和分母总是整数...
  • 你会在一张纸上/在你的脑海中做什么来简化分数?

标签: java fractions simplify


【解决方案1】:

首先,请记住如何将分数缩减为最低项。给定整数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);
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-08
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    相关资源
    最近更新 更多