Results 1 to 3 of 3
  1. #1
    mjunit is offline Member
    Join Date
    Nov 2009
    Posts
    3
    Rep Power
    0

    Unhappy How do i find the reciprocal of a number in java?

    hello,

    I cant seem to find a way to find the reciprocal of a number in java, any ideas?

    For example, finding the reciprocal of 2

    Thanks!

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    The problem is likely that you're doing int division. If you divide an int by an int, you'll get an int. For instance:

    1/2 will = 0
    5/4 will = 1

    To fix this, use double. For the inverse of two, you'll want to do one of these:

    Java Code:
    double invOfTwo = 1.0/2.0;
    
    // or
    invOfTwo = (double) 1 / 2;

  3. #3
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    6

    Default

    Well, the reciprocal of a number is 1 over that number - e.g. the reciprocal of 2 is 1/2.

    You would do this in Java the same way you do it on paper.

    Java Code:
    double number = 2;
    double inverse = 1.0 / number;
    Using 1.0 ensures that the result will be a double, even if "number" is an int.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

Similar Threads

  1. find the greatest and lowest number in 2D array
    By le_albina@hotmail.com in forum New To Java
    Replies: 2
    Last Post: 03-31-2009, 12:09 AM
  2. Find a number from a string
    By florentp in forum New To Java
    Replies: 2
    Last Post: 03-20-2009, 10:01 PM
  3. Find all permutations of a number
    By matzahboy in forum New To Java
    Replies: 6
    Last Post: 12-02-2008, 04:59 AM
  4. Replies: 8
    Last Post: 04-22-2008, 04:21 AM
  5. Find nth root of a number
    By perito in forum New To Java
    Replies: 1
    Last Post: 03-03-2008, 07:51 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
  •