JAVA/개념
JAVA :: Math.random (랜덤 함수)
관리자ID
2024. 3. 20. 14:21
Math.random() : x
0 <= x < 1.0 임의의 실수값을 리턴해주는 함수
예시 :
int num = (int)(Math.random()*10)+1;
1~10 사이의 임의의 수(난수)를 출력하기
0 <= x < 1.0
0 <= x*10 < 10.0 : 0 ~ 9.9999
0 <= (int)(x*10) < 10.0 : 0 ~ 9
0 <= (int)(x*10)+1 < 10.0 : 1 ~ 10
응용 : 가위바위보 프로그램 만들기
public class Exam3 {
public static void main(String[] args) {
int num = (int)(Math.random()*3)+1;
switch(num) {
case 1 : System.out.println("가위"); break;
case 2 : System.out.println("바위"); break;
case 3 : System.out.println("보"); break;
}
}
}