|
-
Decimal to Fraction
I've created a Fraction class that will take a double in the constructor and transform it into a printable fraction. I've got everything working fine except for repeating fractions like 1/3. I know I need to change the code for my Fraction constructor (using doubles), but I'm not sure how.
Here is my fraction class:
public class Fraction
{
int n,d;
public Fraction()
{
n=0;
d=0;
}
public Fraction (double doubleFraction)
{
this.gcd((int)(doubleFraction*100),100);
}
public Fraction (int numerator, int denominator)
{
this.gcd(numerator,denominator);
}
private void gcd (int numerator, int denominator)
{
int highest;
if (denominator>numerator)
highest=denominator;
else
highest=numerator;
for(int x = highest;x>0;x--)
{
if (denominator%x==0 && numerator%x==0)
{
this.n=numerator/x;
this.d=denominator/x;
break;
}
}
}
public String getFraction()
{
int wholeNumber;
if (this.n == this.d)
return("" + 1);
else if (this.d > this.n)
return (this.n + "/" + this.d);
else
{
Fraction test = new Fraction(this.n,this.d);
wholeNumber = (int)(test.n/test.d);
test.gcd(test.n%test.d,test.d);
return (wholeNumber + " " + test.n + "/" + test.d);
}
}
}
Thanks for any help.
Last edited by evenflow58; 12-15-2005 at 10:57 PM.
Similar Threads
-
By malehda3y in forum C++
Replies: 13
Last Post: 12-03-2005, 02:35 PM
-
By Villy Olsson in forum Database
Replies: 4
Last Post: 04-06-2002, 08:01 PM
-
By Peter Farthofer in forum VB Classic
Replies: 2
Last Post: 09-26-2001, 06:08 PM
-
By curtis king in forum Database
Replies: 0
Last Post: 02-25-2001, 12:58 PM
-
By Dante in forum VB Classic
Replies: 2
Last Post: 06-23-2000, 02:45 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks