JAVA_09_임의의 정수 만들기

charl hi·2021년 8월 8일
0

JAVA

목록 보기
9/53

Math.random()

  • 0.0이상 ~1.0미만의 임의의 double값 반환

1이상 ~ 3이하의 임의의 정수 반환하기

0.0 <= Math.random() < 1.0

0.001.. ~ 0.999..

1. 각 변에 *3 을 하기

  • 곱하는 값은 ✨내가 원하는 개별 값의 개수

-> *3

0.0 <= Math.random() * 3 < 3.0

0.001.. ~ 2.999..

2. 각 변에 (int) 붙여서 정수형으로 변환하기

(int)0.0 <= (int)(Math.random() * 3) < (int)3.0

->

0 <= (int)(Math.random() * 3) < 3

0, 1, 2

3. 각 변에 +1을 하기

-> +1

1 <= (int)(Math.random() * 3) + 1< 4

1, 2, 3



public class Ex4_07 {

	public static void main(String[] args) {
		
		// quiz1. 1~10의 정수인 난수 20개 출력
		for(int i=1; i<=20; i++) {
			System.out.print((int)(Math.random()*10)+1+" ");
			//1<= x <11
		}
		System.out.println();
		// quiz2. -5~5의 정수인 난수 20개 출력
		for(int i=1; i<=20; i++) {
			System.out.print((int)(Math.random()*11)-5+" ");
			//-5<= x <6
		}

	}

}

3 6 10 5 3 4 5 7 4 10 4 8 8 7 3 9 8 9 3 2 
-2 -1 -5 1 -5 -3 1 0 0 -1 -5 -1 4 -3 1 -1 2 5 -2 -1 



Ref

0개의 댓글

관련 채용 정보