-
Java Question
One of the rules when working with java is :
( *, /, % ) takes precendence over ( + , - )
So how comes the result produces 2.5, and not 3 (to get 3 i did three/two first = 1.5 and then added 1.5 to it - this follows the above rule
------------------------
int three = 3;
int two = 2;
double result;
result = 1.5 + three/two;
result = 2.5
-------------------------
Am i over looking, or doing something really stupid ? Any ideas ?
-
Try using a double for the vars two and three instead of an int. Should work I think.
Seems three/two is seen as an integer and rounded down?
-
Or another way of looking at it is 2 only goes into 3 one time..el-half is correct, if you want the correct value to come out of the division portion, at least one needs to be a double value.
EDIT: ie 1/3=0, but 1.0/3.0=.3333333e
Another way of doing it would be <var>=2.5 + (double) 3/2;
-
Doing (double) 3/2 will not return the correct result, because Java will calculate the result as an integer division and round down to 1, then cast to a double giving 1.0.
Either specify one of two/three as a double or do the following:
result = 1.5 + (((double) three) / two)
Casting has low precedence in relation to arithmetic operations so it will cast the result if you don't use brackets rather than casting the number.
-
Yep, I forgot to add the brackets, and I posted incorrect info, and I knew better
/me slaps self on head