Question

I am currently watching some tutorials and I am stuck at a part that looks like this:

int x = (int) a_float / an_int;

What will happed if a_float / an_int; is not an integer? Will the number be rounded / floored / weird stuff?

Was it helpful?

Solution

In Java, casting takes precedence over division: http://introcs.cs.princeton.edu/java/11precedence/. This means that the statement can be broken down as follows:

  1. Truncate a_float (basically take the floor and store as an int)
  2. Do integer division by an_int
  3. Assign the resulting int value to x

If you want an_int to be promoted to a float before the operation, then do the division, omit the cast. The result will be a float (which you can than truncate back into an int before assignment):

int x = (float)(a_float / an_int);

is the same as

int x = (float)(a_float / (float)an_int);

You can also read this site for a pretty good explanation of what it all means: http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top