-2

I know getting the reciprocal of an int would go something like this:

int foo = 5;
float recip = 1/foo;

but how would you go about getting the reciprocal of a float? Would it go the same way? Right now I have the user inputting the reciprocal, which is not optimal. Any ideas?

EDIT

For clarification here's some pseudo-code:

float input = 0.25;
int recip = (get reciprocal here);
System.out.println(recip); //should return 4

Thanks!

user2352923
  • 47
  • 1
  • 9
  • integers can't store decimal digits. you can cast, but then you lose data – ItamarG3 Nov 06 '16 at 12:43
  • 2
    `float recip = 1/(float)foo;`. Or `float recip = 1F/foo`. – Boris the Spider Nov 06 '16 at 12:43
  • 1
    `float recip= 1/foo` doesn't give you the reciprocal of an int, it gives you `0`; did you even try that ? And is it so far reaching to try `1/input` ? –  Nov 06 '16 at 14:57
  • @YvesDaoust That wasn't my original question, not what I was looking for and I recall saying "something like this" instead of saying "goes like this". Please read the question. – user2352923 Nov 06 '16 at 20:07

1 Answers1

5

how would you go about converting a float to an int?

That depends on what you want to have happen to the fractional part.

If you want to chop it off, you can cast:

float floatValue = 2.7f;
int value = (int)floatValue;
System.out.println(value); // 2

If you want to round it, use the various rounding methods in the JDK's library, such as Math.round(float).

float floatValue = 2.7f;
int value = Math.round(floatValue);
System.out.println(value); // 3

Re your comment:

I am looking more for a way to find the reciprocal of the value, not the rounded value. For example, if I had 0.25 as my value, then I would like to receive 4 for my output, etc.

If the reciprocal is one over the value, then:

float input = 0.25f;
int recip = (int)(1.0f / input);
System.out.println(recip); // 4

...which chops off any fractional part, or

float input = 0.25f;
int recip = Math.round(1.0f / input);
System.out.println(recip); // 4

...which rounds it. (And there are other rounding methods that give you control over half-up vs. half-down vs. half-even, vs. rounding toward zero rather than positive infinity, etc.)


Side note: There's almost never a good reason to use float as opposed to double. And note that decimal constants, e.g. 2.0, are doubles. If you want floats, put an f at the end: 2.0f. But again: Use double. :-)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875