프로그래밍/JAVA

[Java] Math 클래스

하와이블루 2022. 8. 1. 23:07
728x90

 

 

Math 클래스는 자바에서 사용되는 수학에 관련한 기능을 담고 있는 클래스이다. Math 클래스의 모든 메소드는 static method이므로, 객체를 생성하지 않고 바로 사용이 가능하며, java.lang 패키지에 포함되어 제공된다.

 

 

random() 메소드

random() 메소드는 임의의 실수(0 ~ <1)를 double 타입으로 반환한다.

// 0 <= Math.random() <1
double random = Math.random();
System.out.println("랜덤한 수 : " + random);
// 랜덤한 수 : 0.4095858388261663

// random * 10 // 4.095858388261663
int num = (int)(random * 10);
System.out.println("랜덤한 수 : " + num);
// 랜덤한 수 : 4

// 랜덤한 수를 뽑아 1~45까지 랜덤한 숫자를 추출
int num1 = (int)(random * 45 + 1);
System.out.println(num1);

 


 

floor() 메소드

floor() 메소드는 인수로 전달받은 값의 올림값을 반환한다.

System.out.println(Math.ceil(10.0));      // 10.0

System.out.println(Math.ceil(10.1));      // 11.0

System.out.println(Math.ceil(10.000001)); // 11.0

 

 

ceil() 메소드

ceil() 메소드는 반대로 인수로 전달받은 값의 내림값을 반환한다.

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

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

 

 

round() 메소드

round() 메소드는 전달받은 실수를 소수점 첫째 자리에서 반올림한 정수를 반환한다.

System.out.println(Math.round(10.0));     // 10

System.out.println(Math.round(10.4));     // 10

System.out.println(Math.round(10.5));     // 11

 

 

참고 : http://www.tcpschool.com/java/java_api_math

 

 

 

 

 

728x90