/ JAVAJUNGSUK

Ch4-12. Math.random()

자바의 정석 기초편

0. 목차



Chapter4. 조건문과 반복문

Ch4 - 12. 임의의 정수 만들기 Math.random()



Ch4 - 임의의 정수 만들기 Math.random()


▶ 임의의 정수 = 난수(亂數) : 어지러운 수 → 난수 만들기란?

▷ Math.random() : 0.0과 1.0사이의 임의의 double 값을 반환

0.0 <= Math.random() < 1.0

▶ 예시

▷ 1, 2, 3 정수 출력

0.0 <= Math.random() < 1.0

  • 각 변에 × 3(원하는 개별 값의 개수 : 1, 2, 3 = 3개)+ 1
    0.0 * 3 <= Math.random() * 3 < 1.0 * 3
    0.0 * 3 <= Math.random() * 3 < 1.0 * 3
    0.0 <= Math.random() * 3 < 3.0
    구하고자 하는 건 실수가 아닌 정수
  • 각 변을 int로 형변환+ 1
    (int)0.0 <= (int)(Math.random() * 3) < (int)3.0 + 1
    0 <= (int)(Math.random() * 3) < 3
    구하고자 하는 건 0, 1, 2 가 아닌 1, 2, 3
  • 각 변에 + 1
    0 + 1 <= (int)(Math.random() * 3) + 1 < 3 + 1
    1 <= (int)(Math.random() * 3) + 1 < 4
    1, 2, 3을 구함


▶ 실습

▷ 1 ~ 10 사이의 난수를 20개 출력
for (int i = 1; i < 20; i++) {  // for문을 20번 돌고 빠져나옴

System.out.println((int)(Math.random() * 10) + 1);  // 이걸 20번 돌림
}

// console
6
5
9
3
2
9
7
5
2
4
8
10
5
10
3
10
9
9
1 // 20개 수는 실행할 때 마다 달라짐
  • 계산과정
    (Math.random()) = 0.0 ≤ x < 1.0 = 0.0 ~ 0.999999999999999...
    구하고 싶은 수는 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 총 10개× 10
    (Math.random() * 10) = 0.0 ≤ x < 10.0 = 0.0 ~ 9.999999999999999...
    ((int)Math.random() * 10) = 0 ≤ x < 10 = 0 ~ 9
    ((int)Math.random() * 10) + 1 = 1 ≤ x < 11 = 1 ~ 10
▷ -5 ~ 5 사이의 난수 20개 출력
for (int i = 1; i < 20; i++) {

System.out.println((int)(Math.random() * 11) - 5);
}

// console
4
-4
-5
-2
5
0
-2
3
-4
-1
4
0
4
1
5
4
-5
-1
-3
  • 계산과정
    (Math.random()) = 0.0 ≤ x < 1.0 = 0.0 ~ 0.999999999999999...
    구하고 싶은 수는 -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 총 11개× 11
    (Math.random() * 11) = 0.0 ≤ x < 11.0 = 0.0 ~ 10.999999999999999...
    ((int)Math.random() * 11) = 0 ≤ x < 11 = 0 ~ 10
    ((int)Math.random() * 11) - 5 = -5 ≤ x < 6 = -5 ~ 6