• [Java] Math 클래스

    2025. 2. 13.

    by. hyunji1109

    • Math 클래스의 메서드들은 모두 정적메서드이므로 객체 생성 없이 바로 호출할 수 있다

     

     

    1) 기본 연산

    • Math.abs(x)
      • 절대값 반환
    • Math.max(a, b) / Math.min(a, b)
      • 두 값 중 최대값 또는 최소값 반환

     

    System.out.println(Math.abs(-10));     // 출력: 10
    System.out.println(Math.max(5, 10));   // 출력: 10
    System.out.println(Math.min(5, 10));   // 출력: 5

     

     

     

    2) 거듭제곱 및 제곱근

     

    • Math.pow(base, exponent)
      • base의 exponent 거듭제곱 계산
    • Math.sqrt(x)
      • x의 제곱근 계산

     

     

    System.out.println(Math.pow(2, 3)); // 출력: 8.0
    System.out.println(Math.sqrt(25)); // 출력: 5.0

     

     

    3) 삼각 함수

    • Math.sin(x) / Math.cos(x) / Math.tan(x)
      • 라디안 값을 입력받아 삼각 함수 값 반환
    • Math.asin(x) / Math.acos(x) / Math.atan(x)
      • 역삼각 함수 값 반환

     

    double radians = Math.toRadians(45); // 45도를 라디안으로 변환
    System.out.println(Math.sin(radians)); // 출력: 0.7071067811865475
    System.out.println(Math.cos(radians)); // 출력: 0.7071067811865475

     

     

     

    4) 로그 및 지수 함수

    • Math.log(x)
      • 자연 로그(밑이 e) 계산
    • Math.log10(x)
      • 밑이 10인 로그 계산
    • Math.exp(x)
      • e^x 계산

     

    System.out.println(Math.log(1));    // 출력: 0.0
    System.out.println(Math.log10(100)); // 출력: 2.0
    System.out.println(Math.exp(1));   // 출력: 2.718281828459045 (e)

     

     

    5) 난수 생성

    • Math.random()
      • 0.0 이상 1.0 미만의 난수 생성

     

    System.out.println(Math.random()); // 출력: 0.0 <= x < 1.0 (랜덤값)

     

     

    6) 상수

    • Math.PI
      • 원주율(π) 값
    • Math.E
      • 자연 로그의 밑(e) 값

     

    int randomNum = (int) (Math.random() * 100) + 1;
    System.out.println(randomNum);

    'CS > JAVA' 카테고리의 다른 글

    JAVA 8, JAVA 11  (0) 2025.02.28
    오버로딩(Overloading), 오버라이딩(Overriding)  (0) 2025.02.27
    JAVA(1)  (0) 2025.01.14

    댓글