Simplifying Fractions With java

纵饮孤独 提交于 2019-12-13 06:29:15

问题


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 simplify 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);
        }   
}

回答1:


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




回答2:


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..



来源:https://stackoverflow.com/questions/6882618/simplifying-fractions-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!