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

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


    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


  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Blog Entries
    Rep Power


    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
    Rep Power


    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 -
    writing tools that make writing code a little easier

Similar Threads

  1. find the greatest and lowest number in 2D array
    By in forum New To Java
    Replies: 2
    Last Post: 03-30-2009, 11:09 PM
  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, 03: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