Could someone please explain why in the following line of code, int is used within brackets after the equals sign?
Code:int x = (int)((width/2) + (0.5-Math.random())*width);
Printable View
Could someone please explain why in the following line of code, int is used within brackets after the equals sign?
Code:int x = (int)((width/2) + (0.5-Math.random())*width);
((width/2) + (0.5-Math.random())*width)
Math.random returns a double — we know this is true because we can look up the method in the Math class api and see the return type specified in the first column of the table in the Methods Summary section.
So the expression
(0.5-Math.random())*width)
will evaluate to a double.
For precision the (width/2) term, which may be an int, is grouped into the same expression and the whole thing is cast to an int.
int x = the value over here must be an int so we cast the double expression to the lesser–precision int primitive data type. Going from higher to lower precision requires an explicit cast.