JAVA

[Java] 임의의 정수 만들기

eehdev 2023. 1. 12. 01:30

     임의의 정수 만들기 → 난수     

  • random() → 0 <= random() <1 에 있는 값을 나타냄
  • 0.0 ≤ Math.random() < 1.0 → 0.0과 1.0 사이의 임의의 double값을 반환
  • 원하는 범위에 있는 난수를 구하기
// 1~3사이 정수

//#1. 각 변에 3을 곱한다
	 0.0 <= Math.random() < 3.0            // 0.0 ~ 2.999...
//#2. 각 변을 int 형으로 형변환
	0 <= (int)(Math.random() * 3) < 3      // 0 ~ 2
//#3. 원하는 범위는 1~3사이. 따라서 각 변에 1씩 더한다
	1 <= (int)(Math.random() * 3) +1 < 4   // 1, 2, 3

(int)(Math.random() * 구하려는 범위 숫자) + 처음 시작하려는 숫자

더보기

예제1 ) 1~10 사이의 난수를 10개 출력하시오

//  1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for(int i=1; i<=10; i++) {
		System.out.println(Math.random());	// 0.0<=x<1.0
		System.out.println(Math.random()*10);	// 0.0<=x<10.0
		System.out.println((int)(Math.random()*10));	// 0<=x<10, 0~9 범위
		System.out.println((int)(Math.random()*10)+1);	// 1<=x<11, 1~10 범위
	}

 

예제2) -5 ~ 5 사이의 난수를 10개 출력하시오

//	-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5  => 11개
	for(int i=1; i<=10; i++) {
		System.out.println((int)(Math.random()*11)); //0<=x<11, 0~10
		System.out.println((int)(Math.random()*11)-5); //-5<=x<6, -5~5
	}
더보기
public static void main(String[] args) {

		for (int i = 1; i <= 6; i++) {
			int lotto = (int) (Math.random() * 45) + 1;
			System.out.println(lotto + " ");
		}
	}