Jump to content

Sorry, you're going to have to give me a little more to work with. Try to explain more about what you're trying to do. Show some code if you can as that may also help.

i don't really have any code, but i'm building a fraction class and it has to return a double floating point value

Link to post
Share on other sites

i don't really have any code, but i'm building a fraction class and it has to return a double floating point value

 

Ok, well if it's a simple fractions class then I'll assume both the numerator and denominator are integers.

 

So in your function you should just be able to do

return (double) numerator/denominator;

The "(double)" part will cast the numerator to the double type. When division happens between a double and an int, it's result will be a double.

// This prints 0 because it's integer division (cuts the result off at the decimal place)System.out.println( 1/2 );// All these print 0.5 because it does floating point division when one or both numbers are a doubleSystem.out.println( 1.0/2 );System.out.println( 1/2.0 );System.out.println( 1.0/2.0 );System.out.println( (double)1/2 );System.out.println( 1/(double)2 );

Note that the cast happens before the division. So

// This casts 1 to a double before dividing by two which results in 0.5(double) 1 / 2// This does the division first resulting in zero, then casts that result of zero to a double. So 0.0(double) (1 / 2)
Link to post
Share on other sites

 

like put return (double) numerator/denominator in 

public double toDouble{}

 

Yeah the function would look something like

public double toDouble() {    return (double) numerator/denominator;}

Assuming that the numerator and denominator are fields in your class. If not, you'd have to pass them in as parameters

public double toDouble(int numerator, int denominator) {    return (double) numerator/denominator;}

Note that you should also handle the "division by zero" error that can occur.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×