How does (int)(Math.random() + 0.5); work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How does (int)(Math.random() + 0.5); work?

Apparently it randomly generates 0 or 1, but I don’t understand how it does this.

7th Aug 2019, 1:42 PM
Samuel
Samuel - avatar
1 Answer
+ 3
Math.random returns a number between 0 and 0.999.. If Math.random returns (for example) 0.3 and you add 0.5 to it, you get 0.8 - Explicit conversions turns 0.8 int to 0, dropping all data after 0. If math random returns 0.7 and you add 0.5, you get 1.2 Explicit conversion will drop everything after 1 and you get result 1
7th Aug 2019, 2:04 PM
HNNX 🐿
HNNX 🐿 - avatar