开发者

Simplifying Fractions With java

Hey guys I am working on a SW here I am kinda in need of help, you see we need to make a method where we are gonna simplify fractions. any idea how? here's my code as of now (don't mind the dvalue Method it is already finsih all I need is the simpli开发者_C百科fy method)

public class Fraction {

    public int num;
    public int den;
    public double dValue;

    public void display()
    {
        System.out.println("Numerator: "+num);
        System.out.println("Denominator: "+den);
    }

    public double dValue()
    {
        dValue = (double)num/den;
        return dValue;
    }


}

public class FractionTest {

        public static void main(String args[])
        {
            Fraction f = new Fraction();
            f.num = 50;
            f.den = 100;
            f.display();

            double d = f.dValue();
            System.out.println(d);
        }   
}


Simplifying fractions is easy if you can folow the steps:

  1. find gcd of both num and den, so you have gcd=GCDFind(gcd, num);
  2. now, if gcd==1, then the fraction cannot be simplified (it is already in simplified form).
  3. if gcd > 1, then newNum = num/gcd; and newDen = den/gcd;

It's all you need I think.

The gcd stands for Greates Common Divisor... Code easily findable, and I just googled JavaScript implentation working this way in few seconds: http://www.calculla.com/en/fraction


You could have a look at these links, they can be helpful

  1. http://www.daniweb.com/software-development/java/threads/13663
  2. http://www.dreamincode.net/forums/topic/64342-reducing-a-fraction/
  3. simplifying fractions in Java

and many more..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜