Type Casting Math.random?

I looked around the questions on this site and could not find the answer I was looking for about the type that distinguishes the method Math.random()from double to int. My question is: why does it Math.randomreturn only 0 without parentheses, while it returns random numbers when it is contained in parentheses? The first part of the code returns 0:

int number; 
number = (int) Math.random() * 10; 
System.out.println("\nThe random number is " + number);

This code works, however:

int number; 
number = (int) (Math.random() * 10); 
System.out.println("\nThe random number is " + number);

It should be noted that I saw several different code fragments during typing, according to which some programmers use both casting methods.

+4
source share
2 answers

This code:

number = (int) Math.random() * 10; 

first computes this:

(int) Math.random()

Math.random() 0 1, 1, int, 0. , 10 0, 0.

+6

Math.random() 0 1. (Math.random() * 10) int, , Math.random. . , , 0.3, Math.random, 0. , 0,3 10, 3. .

+1

Source: https://habr.com/ru/post/1548161/


All Articles