Java 分数加法公式有问题

Java Fraction Addition Formula Trouble

我有一个 class 项目,您必须从用户那里收到两个分母不同的分数,将它们相加并以最小公分母输出。由于我们必须仅使用我们已经涵盖的章节中的原则,所以我不能做分数 class 所以请不要建议。基本上我需要制作一个方法来将分数加在一起。我只是想把这些方法的基本公式写下来,所以这里是我现在拥有的所有代码。非常感谢任何建议、提示或帮助。 :-)

//Joseph Biancardi
//IS1300 Spring 2015
public class FractionAddition{
public static void main(String[] args) {
    final int n1 = 2;
    final int n2 = 3;
    final int d1 = 3;
    final int d2 = 6;
    int c = 0;
    int e1 = 0;
    int e2 = 0;
    while(c == 0) {
        if(e1 == e2) {
            c = 2;
        }
        e1 =+ d1;
        if(e1 == e2) {
            c = 1;
        }
        e2 =+ d2;

    }
    System.out.println(e1 + " " + e2);
    int f1 = e1 / d1;
    int f2 = e2 / d2;
    int g1 = n1 * f1;
    int g2 = n2 * f2;
    int final1 = g1 + g2;
    System.out.println(n1 + " " + n2 + " equals" + " " + final1);
    System.out.println(d1 + " " + d2 + " equals" + " " + e1);
        }
    }

您查找LCM的方式不正确。您应该这样计算 e

private static long gcd(long a, long b)
{
    while (b > 0)
    {
        long temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}


private static long lcm(long a, long b)
{
    return a * (b / gcd(a, b));
}
...
e = lcm(d1, d2); //denominator
int f1 = e / d1;
int f2 = e / d2;
int g1 = n1 * f1;
int g2 = n2 * f2;
int final1 = g1 + g2;
int k = gcd(final1, e);
int final_nominator = final1 / k;
int final_denominator = e / k;

请注意,我的gcd算法不是最优算法,其速度可以显着提高。