We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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.
Comments
Addendum: decimal point
.
, scientific notatione
, suffixesf
&d
; if any of them are present in a literal, that makes it a fractional value: L-)0.0
or0.
or.0
1e-3
or1E-3
5f
or5F
-10d
or-10D
Processing IDE (PDE)'s pre-processor automatically suffix all literals w/
f
when there's a point.
ore
anywhere in that literal for ".pde" files before compilation, unless they're suffixed already. :-B