Java Math Method

Yong Lee·2025년 7월 29일

코딩테스트 문제, 자바로 개발을 할 때 기억해두면 좋은 유용한 메서드들을 정리해보려고 합니다.

절대값

Math.abs(-5); // 5
Math.abs(3.14); // 3.14

최댓값/최솟값

Math.max(2, 9) // 9
Math.min(2, 9) // 2

제곱/제곱근

Math.pow(2, 3); // 8.0 (2^3)
Math.sqrt(16);  // 4.0 (√16)

반올림/올림/내림

long r1 = Math.round(3.6); // 4 (long 반환)
double r2 = Math.ceil(3.1); // 4.0
double r3 = Math.floor(3.9); // 3.0

Math.round(3.6)은 결과가 정수 long 타입이고, Math.ceil()과 Math.floor()는 double을 반환합니다.
즉 round는 정수로 반환하고, ceil과 floor는 실수로 반환한다는 것을 기억하면 좋습니다.

랜덤 숫자

double r = Math.random(); // 0.0 <= r < 1.0
int n = (int)(Math.random() * 10); // 0 ~ 9 랜덤 정수

로그/지수 함수

Math.log(10);       // 자연로그 (ln 10)
Math.log10(100);    // 밑이 10인 로그 (log₁₀ 100 = 2)
Math.exp(2);        // e^2
profile
오늘은 어떤 새로운 것이 나를 즐겁게 할까?

0개의 댓글