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:
- find gcd of both num and den, so you have gcd=GCDFind(gcd, num);
- now, if gcd==1, then the fraction cannot be simplified (it is already in simplified form).
- 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
- http://www.daniweb.com/software-development/java/threads/13663
- http://www.dreamincode.net/forums/topic/64342-reducing-a-fraction/
- simplifying fractions in Java
and many more..
精彩评论