Math 클래스 란?

Math 클래스는 수학에서 자주 사용하는 상수들과 함수들을 미리 구현해 놓은 클래스다.

Math 클래스의 모든 메소드는 클래스 메소드(static method)이므로,

객체를 생성하지 않고도 바로 사용할 수 있다.

이러한 Math 클래스는 java.lang 패키지에 포함되어 제공된다.

Math.random()

0.0 이상 1.0 미만의 범위(0.0 ~ 0.999…)에서 임의의 double형 값을 하나 생성하여 반환한다.

System.out.println((int)(Math.random() * 100)); // 0 ~ 99

Random ran = new Random();
System.out.println(ran.nextInt(100));           // 0 ~ 99

(int)(Math.random() * 6);       // 0 ~ 5
((int)(Math.random() * 6) + 1); // 1 ~ 6
((int)(Math.random() * 6) + 3); // 3 ~ 8

Math.abs()

abs() 메소드는 전달된 값이 음수이면 그 값의 절댓값을 반환하며,

전달된 값이 양수이면 전달된 값을 그대로 반환한다.

System.out.println(Math.abs(10));    // 10
System.out.println(Math.abs(-10));   // 10
System.out.println(Math.abs(-3.14)); // 3.14

Math.floor()

floor() 메소드는 인수로 전달받은 값과 같거나 작은 수 중에서 가장 큰 정수를 반환한다.

System.out.println(Math.floor(10.0));     // 10.0
System.out.println(Math.floor(10.9));     // 10.0