자바
난수 발생 (2022-06-23)
Kiwisae
2022. 6. 23. 10:51
난수 발생 공식
Math.random();
// 예를 들어 주사위의 값을 뽑는다면 (1~6)
int num = (int)(Math.random() * 6) + 1 ;
// 난수 발생 공식
// 1) 난수 = (정수)(Math.random() * (상한값 - 하한값 + 1)) + 하한값 ;
// 2) 1.0 <= Math.random() < 6.0 <- 실수형태
// 1 <= ~ < 6 <- 정수형태
추가로
System.out.println("E = " +Math.E); // E값.
System.out.println("PI = " +Math.PI);// PI값
System.out.println(Math.random());// 난수발생
api 문서에서 찾아보면 E와 PI는 정적 필드 (static fields)로 분류가 되어 있는데 이런 것들은 객체를 생성할 필요가 없다.
클래스 명으로 접근해서 사용
math m = new math(); 오류 발생
math.e, math.pi 이런 식으로 사용
random 역시 static이 붙은것으로 명시 되어 있는데,
random r = new random(); 오류 발생
random() 이렇게 사용