Which means assign Math.random ()> 0.5 to a variable?
What Does Math.random() > 0.5;
mean in a boolean
?
Here is an example:
class Pro {
public static void main(String[] args) {
int numero = 10;
boolean[] array = new boolean[numero];
for(int i= 0; i< array.length; i++) {
array[i] = Math.random() > 0.5;
System.out.print(array[i] + "\t");
}
}
}
3 answers
Math.random()
will generate a value between 0 and 0.999999(tends to the limit of 1, but does not reach 1).
Soon your code snippet:
array[i] = Math.random() > 0.5;
Is checking if the value generated by the function random
is greater than 0.5
If larger, true
is set to that array position. Otherwise, Arrow as false
.
The intention of the author of the code is that each element of the Vector has a 50% chance of being true
and a 50% chance of being false
.
In practice, this isn't going to be totally true for mathematical reasons, but it's close enough.
As for the Code, Math.random() > 0.5
is a expression that returns a boolean value, that is, true or false.
As with any mathematical expression, you can assign the result to a variable of the same type generated by the expression.
For example, the snippet:
boolean var = Math.random() > 0.5;
Is the "summary" form of:
boolean var;
if (Math.random() > 0.5) {
var = true;
} else {
var = false;
}
Means exactly one boolean. What is the response of the expression Math.random() > 0.5
? It will be true
or false
, right? It will check if the number drawn is greater than half and get the result if it is true or false, then the answer will be saved in the appropriate variable.