# Thread: How do i find the reciprocal of a number in java?

1. Member Join Date
Nov 2009
Posts
3
Rep Power
0

## 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!  Reply With Quote

2. ## 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;```  Reply With Quote

3. ## 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.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•