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!

Printable View

- 11-25-2009, 10:40 PMmjunitHow 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! - 11-25-2009, 10:50 PMFubarable
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:

Code:`double invOfTwo = 1.0/2.0;`

// or

invOfTwo = (double) 1 / 2;

- 11-26-2009, 03:43 AMCodesAway
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.

Code:`double number = 2;`

double inverse = 1.0 / number;