简化一小部分,Java

时间:2016-05-07 22:48:15

标签: java

我正在做一个学校项目,其中我添加了2个分数,需要简化答案。到目前为止,我有很多代码,但有一些情况下某些分数没有正确简化。例如,1/4 + 1/6 1ill给出5/6而不是5/12。您能否查看我的代码是否有任何可能的错误或指示?

public int num1, num2, denom1, denom2, numSum, denomAns, denomSimp, gcd;

public Fraction(int a1, int a2, int a3, int a4, int a5, int a6) {
    this.num1 = a1;
    this.num2 = a2;
    this.denom1 = a3;
    this.denom2 = a4;
    this.numSum = a5;
    this.denomAns = a6;
}

public void simplify() {

    if (denom1 == denom2) {
        denomAns = denom1;
        numSum = num1 + num2;
    } else {
        denomAns = denom1 * denom2;
        num1 = num1 * denom2;
        num2 = num2 * denom1;
        numSum = num1 + num2;
    }
    int tempNum = numSum, tempDenom = denomAns;
    if (tempNum == 0) {
        gcd = tempDenom;
    } else {
        while (tempDenom != 0) {
            if (tempNum > tempDenom) {
                tempNum = tempNum - tempDenom;
            } else {
                tempDenom = tempDenom - tempNum;
            }
        }
        gcd = tempNum;
    }
    denomSimp = denomAns / gcd;
    numSum = numSum / gcd;
}

1 个答案:

答案 0 :(得分:0)

package test;

public class Fraction {

    private int num1;
    private int num2;
    private int denom1;
    private int denom2;

    private int num;
    private int denom;

    public Fraction(int num1, int num2, int denom1, int denom2) {
        this.num1 = num1;
        this.num2 = num2;
        this.denom1 = denom1;
        this.denom2 = denom2;
    }

    public void sum() { //sum the two fractions
        num = (num1 * denom2) + (num2 * denom1);
        denom = denom1 * denom2;
    }

    public void simplify() {

        int gcd = gcd(num, denom);

        num = num / gcd;
        denom = denom / gcd;
    }

    public int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    public static void main(String[] args) {
        Fraction fraction = new Fraction(1,1,4,6); // 1/4 and 1/6
        fraction.sum();
        fraction.simplify();
        System.out.println("Simplified : " + fraction.getNumSimp() + "/" + fraction.getDenomSimp());
    }

    public int getNumSimp() {
        return num;
    }

    public int getDenomSimp() {
        return denom;
    }

}