Integer Division (Why does 2 / 5 = 0?)

edited September 4 in Common Questions

Taken from the Processing WIKI here: https://github.com/processing/processing/wiki/Troubleshooting

Why does 2 / 5 = 0 instead of 0.4?

The result of dividing two integers will always be another integer:

int a = 2;
int b = 5;
int result = a / b;
// result is zero

While somewhat confusing at first, this is later useful for more advanced programming.

To get fractions, use a 'float' instead:

float a = 2.0;
float b = 5.0;
float result = a / b;
// 'result' will be 0.4

It is not enough to just divide two integers and set them to a float:

float y = 2 / 5;

In this case, integer 2 is divided by 5, which is zero, and then zero is assigned to a float. The number doesn't become a float until the left hand side of the = sign. On the other hand, this:

float y = 2.0 / 5;

will work just fine. In this case, Java sees that 2.0 is a float, so it also converts the 5 to a float so that they can be divided, which makes it identical to:

float y = 2.0 / 5.0;

and because floats are being used on the right hand side, the result will be a float, even before it gets to the left hand side.

Tagged:

Comments

  • edited September 4

    Addendum: decimal point ., scientific notation e, suffixes f & d; if any of them are present in a literal, that makes it a fractional value: L-)

    1. 0.0 or 0. or .0
    2. 1e-3 or 1E-3
    3. 5f or 5F
    4. -10d or -10D

    Processing IDE (PDE)'s pre-processor automatically suffix all literals w/ f when there's a point . or e anywhere in that literal for ".pde" files before compilation, unless they're suffixed already. :-B

This discussion has been closed.