Math.random() - Solon City Schools

How do I generate an
integer from 1 to n?
Yay, Math.random()!!!!
What does Math.random()give me?
Answer:
0
A double in this range: [0, 1)
1
Give me a few sample Math.random() values:
.5
.1
.751347988
Question 1:
What could be stored in x after this?
x =
Answer:
0
6*Math.random()
A double in this range: [0, 6)
6
Sample 6*Math.random() values:
.5
times 6 = 3.0
.1
times 6 = 0.6
.751347988 times 6 = 4.508087924
Question 2:
How do you make x an integer?
x =
Answer:
6*Math.random()
(int) (6*Math.random())
What is the range of answers this code could generate?:
0 to 5
0
6
Sample (int)(6*Math.random()) values:
.5
times 6 = 3.0 becomes 3
.1
times 6 = 0.6 becomes 0
.751347988 times 6 = 4.508087924
becomes 4
Question 3:
How do you make x from 1 to 6?
x = (int)(6*Math.random())
Answer:
0
(int)(6*Math.random()) +1
6
Sample (int)(6*Math.random())+1 values:
.5
times 6 = 3.0 becomes 3 + 1
.1
times 6 = 0.6 becomes 0 + 1
.751347988 times 6 = 4.508087924
becomes 4 + 1
Question 4:
What is the range of values that could be
in sum after this code executes?
int i = 1, sum = 0;
do
{
sum += (int)(3 * Math.random()) + 1;
Answer: Number of iterations: 2
i++;
1st iteration: 1, 2, or 3
}
2nd iteration: 1, 2, or 3
while (i < 3);
sum: 2 to 6
//sum will be in this range of values: [
]